我尝试使用以下代码使用增量搜索技术找到方程式的根。当我将精度设置为5或7位数字时,代码可以正常工作。但是,当我将精度设置为6位数字时,代码无法提供适当的值,在这种情况下,我应该怎么做。代码如下:
import numpy as np
import matplotlib.pyplot as mpl
import prettytable as PT
func_input=input("Function i/p (in numpy notation): ")
fn = eval("lambda x:" + func_input)
## (667.38/x)*(1-np.exp((-0.146843)*x))-40
print ("Function is: ",func_input)
p=int(input("Precision: "))
print("Refer to the graph of the function for the start value")
x1=float(input("Start From: "))
i=0
m=x1
while (m<=x1+4.0):
m=x1+i*(10**(-p))
y=round(fn(m),p)
if (y==0):
break
i+=1
print("The root is: ",m)
对于各种精度值,我得到以下输出:
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
= RESTART: C:/Users/3D/Desktop/Rushikesh/Python Programs/Roots of Equation/Bracketing Methods/05_Incremental Search.py
Function i/p (in numpy notation): (667.38/x)*(1-np.exp((-0.146843)*x))-40
Function is: (667.38/x)*(1-np.exp((-0.146843)*x))-40
Precision: 5
Refer to the graph of the function for the start value
Start From: 14.5
The root is: 14.78021
>>>
= RESTART: C:/Users/3D/Desktop/Rushikesh/Python Programs/Roots of Equation/Bracketing Methods/05_Incremental Search.py
Function i/p (in numpy notation): (667.38/x)*(1-np.exp((-0.146843)*x))-40
Function is: (667.38/x)*(1-np.exp((-0.146843)*x))-40
Precision: 7
Refer to the graph of the function for the start value
Start From: 14.5
The root is: 14.7802086
>>>
= RESTART: C:/Users/3D/Desktop/Rushikesh/Python Programs/Roots of Equation/Bracketing Methods/05_Incremental Search.py
Function i/p (in numpy notation): (667.38/x)*(1-np.exp((-0.146843)*x))-40
Function is: (667.38/x)*(1-np.exp((-0.146843)*x))-40
Precision: 6
Refer to the graph of the function for the start value
Start From: 14.5
The root is: 18.500001
>>>
最佳答案
舍入似乎导致例程跳过终止情况(因此y刚好在零以下和零以上而实际上未达到零)。
建议用y == 0
替换math.close()
测试,或仅返回x以找到的最低幅度y(即最接近零)。
希望这可以帮助 :-)
关于python - 四舍五入到6位数字有什么问题吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59926033/