在Python中使用Newton方法,没有错误消息,但不打印/p

2024-04-20 00:31:42 发布

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

我试图用牛顿的方法,用Python来近似Colebrook方程的根。目前代码没有错误,但也没有打印/绘图。我明白这可能是一个个案,并感谢所有的帮助提前! enter image description here

numpy as np
import random
import matplotlib.pyplot as plt

#Define Variables, k=e/D, E+04<=x=Re<=E+07
k=0.0001

#Define Colebrook function, f=x=independent variable
def f(x):
    return -0.86*(np.log(( 2.51/(Re*np.sqrt(x))) + ( k/3.7))) - (1/np.sqrt(x))

#Define derivative function by definition & approximation
def derivative(f,x,h):
    return (f(x + h) - f(x))/h

#Newton's method approximation with initial gussed x value
x=0.01
for Re in range (10^4,10^7, 10000):
    m=derivative(f,x,h=0.01)
    b=f(x)-m*x #y=mx+b
    newx=-b/m #new x value determined by the tangent line
    if abs(g(newx))<= (1/10000000000):
        print ('root =' + newx)
    else:
        x=newx

#plot
for Re in range (10^4, 10^7,10000):
    x=newx
    plt.plot (f(x))   

我已经知道我要找的根大约是0.03。你知道吗


Tags: importrebyreturndefasnpfunction
2条回答

最明显的问题是:

range (10^4,10^7, 10000)

没有输出。您应该查看range的定义:第三个输入是步长,而不是步数;我想您应该使用“power”、10**410**7^符号是按位异或。你知道吗

我看到了几个问题:

  • 正如mdurant所指出的,您的范围需要一些适当的重写。你知道吗
  • 您的第一个循环调用一个g(x)函数,而您在任何地方都没有定义它。你知道吗
  • 即使在那之后,你的第二个循环说“让x是xnew,然后把f(x)加到绘图中,重复多次(不改变x的值)”。你知道吗
  • 而且,我认为plt.绘图()只是将数据添加到绘图中。你需要节目()查看图表。您可能还需要定义绘图轴、颜色等。使用matplotlib的一些示例脚本可以向您显示语法。你知道吗

相关问题 更多 >