四舍五入是否有问题?

问题描述 投票:1回答:1

我尝试了以下代码,使用增量搜索技术找到方程式的根。当我将精度设置为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
>>> 
python rounding precision numerical-methods
1个回答
1
投票

似乎舍入导致例程跳过终止情况(因此y刚好在零以下并且刚好在零以上而实际上未达到零)。

建议用y == 0代替math.close()测试,或者只返回x以找到最低的幅度y(即最接近零)。

希望这会有所帮助:-)

© www.soinside.com 2019 - 2024. All rights reserved.