如何将此代码放入函数中

2024-04-26 15:09:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把它放到一个函数newton(x)中,允许用户输入x的值

from math import *
x=20
for iteration in range(1, 1001):

        xnew = x - (((3*10**-5)*exp((log1p(10**3/(3*10**-5)))*(1-exp(-.12*x))))-1)/(.12*(3*10**-5)*exp((log1p(10**3/(3*10**-5))))*(1-exp(-.12*x)*(-.12*x))) # the Newton-Raphson's formula
        print("Error",x-xnew," Xn:   ", xnew)
        if abs(xnew - x) < 0.000001:
            break  

        x = xnew  
print('The root : %0.5f' % xnew)
print('The number of iterations : %d' % iteration)

Tags: the函数用户infromimportforrange
1条回答
网友
1楼 · 发布于 2024-04-26 15:09:04

您可以将其设置为返回2元组的函数:

from math import *

def newton(x):
    xnew = iteration = None
    for iteration in range(1, 1001):
            xnew = x - (((3*10**-5)*exp((log1p(10**3/(3*10**-5)))*(1-exp(-.12*x))))-1)/(.12*(3*10**-5)*exp((log1p(10**3/(3*10**-5))))*(1-exp(-.12*x)*(-.12*x))) # the Newton-Raphson's formula
            print("Error",x-xnew," Xn:   ", xnew)
            if abs(xnew - x) < 0.000001:
                break  
            x = xnew
    return xnew, iteration

xnew, iteration = newton(20)
print('The root : %0.5f' % xnew)
print('The number of iterations : %d' % iteration)

相关问题 更多 >