Question

I had a question concerning the results of a polynomial equation while using python/numpy. I have defined a function using a polynomial having a rather small leading coefficient. The following is my code and the equation:

import matplotlib.pyplot as plt
import numpy as np 

def myfunction(X):
    return 9.06043895*10**(-9)*X**6-1.67073053*10**(-6)*X**5 + \
          7.49688511*10**(-5)*X**4 + 7.97984114*10**(-4)*X**3 - \
          6.07927087*10**(-2)*X**2 - 0.415861627*X + 80.62563

Input = np.arange(0, 100, 1)
Output = myfunction(Input)

plt.plot(Input, Output)

This yields the following plot:

enter image description here

The error seems to be in the way that the resultant Y is calculated as the array itself is off. (The values match the plot, but are in correct)

Sample of the exact same equation plotted using WolframAlpha: (literal copy/paste from above minus the \'s and returns)

enter image description here

Can anyone help shed some light on this problem?

I have a feeling there may be some truncations possibly while handling the function, but I feel that this equation is not that bad...

Thank you all for your time and hopefully assistance.

Was it helpful?

Solution

This is an int vs. float issue. You're getting integer overflow:

>>> np.int32(100)**6
-727379968
>>> np.float32(100)**6
1000000000000.0

because np.arange(0, 100, 1) is giving you integers.

You can make them floats however you like-- I usually use np.arange(0, 100, 1.0), but to be honest I prefer np.linspace.

With floats, I get:

corrected curve

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top