简体   繁体   中英

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. 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.5279390283223464

I have no idea why there is a different result for the same formula and the value. The correct is 0.5279390283223464.

To make your code work correctly use bigger datatype ie (dtype="float64"), edit your code to:

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

or if you want the 2 results to match in precision add [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

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"

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>>>

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

which support my point of view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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