Solving math and got a different output from Python and Wolfram Alpha

523 views Asked by At

I found this picture on 9gag and I decided to write a python code to see if this is true

enter image description here

However, when I run the following python code, I got a different result from what I got from Wolfram Alpha

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return  (18111/2)*(x**4) - 90555*(x**3) + (633885/2)*(x**2) - 452773*x + 217331

for i in range(0,5):
    print f(i)

Output:

217331
0
-7
-40
-129
217016

And here's the link to my Wolfram Alpha query link

Notice that I copied and pasted my equation string directly from my Python code to Wolfram alpha and it seems to interpreted correctly. So I highly doubt that the fault is within my Python code.

1

There are 1 answers

1
falsetru On BEST ANSWER

In Python 2.x, int / int returns a int. (truncate number below decimal point)

>>> 18111/2
9055

To get the number you want, you need to use float.

>>> 18111/2.0
9055.5

Or, you can change the behavior using from __future__ import ... statement:

>>> from __future__ import division
>>> 18111 / 2
9055.5

BTW, to iterate from 1 to 5. you need to use range(1, 6), not range(0, 5).

>>> range(0, 5)
[0, 1, 2, 3, 4]
>>> range(1, 6)
[1, 2, 3, 4, 5]