0

I have this function that takes in an x value and returns an output y value.

def function(x):
    y = math.cos(x**2/2)/(math.log(x+2,2))
    return y

When I call the function, I get:

print function(1)
>> 0.630929753571

But WolframAlpha has the value at x = 1 to be 0.553693

Which is the correct value?

martineau
  • 119,623
  • 25
  • 170
  • 301
JasonDor
  • 19
  • 2

4 Answers4

0

This is because you are using Python 2, where the / operator does integer division. This would give you the correct answer in Python 3:

>>> def f(x):
...   y = math.cos(x**2/2)/(math.log(x+2,2))
...   return y
...
>>> f(1)
0.5536929495121011

In Python 3, using the // operator, does floor division:

>>> def f(x):
...   y = math.cos(x**2//2)/(math.log(x+2,2))
...   return y
...
>>> f(1)
0.6309297535714574
>>>

In Python 2, use y = math.cos(x**2/ 2.0) / (math.log(x+2,2))

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
0

you are dividing an int by another int which is greater: 1 / 2 and therefore getting the cosine of zero since python 2.7 does not evaluate integer divisions as floating point. Try:

def function(x):
    y = math.cos(x ** 2 / 2.0) / (math.log(x + 2, 2))
    return y
kiliantics
  • 1,148
  • 1
  • 8
  • 11
0

Python 2 division operator does integer division, unless you tell it it's a float.

If you change to x**2/2.0 you will get the correct answer, like wolfram alfa.

Israel Unterman
  • 13,158
  • 4
  • 28
  • 35
0

Python 2 rounds to integer when you divide integer by integer so use one float number (i.e 2.0) when you divide to get correct result

import math

def function(x):
    y = math.cos(x**2/2.0)/(math.log(x+2,2))
    return y

print function(1)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
furas
  • 134,197
  • 12
  • 106
  • 148