简体   繁体   English

公式为同一变量返回不同的值

[英]Equation return different values for the same variable

I'm trying to create a chart but it looks incorrect. 我正在尝试创建一个图表,但它看起来不正确。 For the range(0, 1000000) the chart should be starts at 0 and ends at 1 at x-axis, but it has negative values. 对于范围(0,1000000),图表应从0开始并在x轴处结束,但它具有负值。 In the begging it's OK, but after some value, it gets wrong. 在乞讨中它没关系,但经过一些价值,它就会出错。

I tried to manually calculate specific values and found out that there is a different result for the same value in the equation. 我试图手动计算特定值,并发现方程中相同值的结果不同。 Here is an example: 这是一个例子:

import numpy as np
import matplotlib.pyplot as plt

def graph(formula, x_range):
    x = np.array(x_range)
    y = eval(formula)
    print(y)
    plt.plot(x, y)
    plt.show()

formula = '1-((2**32-1)/2**32)**(x*(x-1)/2)'
graph(formula, range(80300, 80301))

x = 80300
print(eval(formula))

There is a different result for the same value, here is the console output: 对于相同的值有不同的结果,这是控制台输出:

[-0.28319476] [-0.28319476]

0.5279390283223464 0.5279390283223464

I have no idea why there is a different result for the same formula and the value. 我不知道为什么相同的公式和价值会有不同的结果。 The correct is 0.5279390283223464. 正确的是0.5279390283223464。

To make your code work correctly use bigger datatype ie (dtype="float64"), edit your code to: 要使代码正常工作,请使用更大的数据类型,即(dtype =“float64”),将代码编辑为:

x = np.array(x_range, dtype="float64")

or if you want the 2 results to match in precision add [0] 或者如果你想让2个结果在精度上匹配加[0]

x = np.array(x_range, dtype="float64")[0]
x = np.array(x_range, dtype="float32")[0]

to understand why, read below: 了解原因,请阅读以下内容:

if you change formula in your code to simple one for example (formula = "x + 100") you will get correct results 如果您将代码中的公式更改为简单的公式(例如,公式=“x + 100”),您将获得正确的结果

what does this mean? 这是什么意思? it means that your formula which is '1-((2 32-1)/2 32)**(x*(x-1)/2)' cause an overflow in numpy "numpy built in C not python" 这意味着你的公式'1 - ((2 32-1)/ 2 32)**(x *(x-1)/ 2)'导致numpy“numpy内置C而不是python”的溢出

i tried the following code to narrow problem possibilities: 我尝试了以下代码来缩小问题的可能性:

formula = '1-((2**32-1)/2**32)**(x*(x-1)/2)'
x = 80300
print(eval(formula))
x = np.array(range(80300, 80301))[0]
print(eval(formula))

output from sublime Text>>> 来自sublime Text >>>的输出

0.5279390283223464
RuntimeWarning: overflow encountered in long_scalars
import numpy as np
-0.28319476138546906

which support my point of view 这支持了我的观点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM