muhzi
muhzi

Reputation: 129

Calculation of infinite series using loops in python

I wish to make the code for a function that calculates the following infinite series:

enter image description here

Which converges to "sin(x)". I wrote the code for getting the value for x:

import math

def zero_to_infinity():
    i = 0
    while True:
        yield i
        i += 1

def CalcMYSeries(x):
    res, temp = 0, 0
    for i in zero_to_infinity():
        res += (((-1)**i)*(x**(2*i+1)))/math.factorial(2*i+1)
        if res == temp:
            break
        temp = res
    return res

the code works OK with small values (e.g) 10, 20. However; for large values it generates false numbers. Here is a sample of the output:

>> CalcMYSeries(10): -0.54402111088927
>> sin(10) =  -0.5440211108893698
>> CalcMYSeries(40): -3.282209134433358
>> sin(40) =  0.7451131604793488

Why is the output behaving as such? are bits being omitted while doing the calculations with larger numbers?

Upvotes: 0

Views: 1096

Answers (2)

Alexey
Alexey

Reputation: 409

when x == 40 and i == 17,

(((-1)**i)*(x**(2*i+1)))/math.factorial(2*i+1)==-1.1425285155674632e+16 

when x == 39 and i == 17,

(((-1)**i)*(x**(2*i+1)))/math.factorial(2*i+1)==-4710083405001725.0

So, when x > 39, there are too big numbers in calculations and float number loses the precision valuable enough for later steps.

Upvotes: 0

jkm
jkm

Reputation: 704

Not how I'd put it, but yes. Floats have finite precision, after a certain point your calculations start getting affected by the inexactness of the binary representation.

Use the built-in Decimal module to work with really small fractions that need to be kept precise.

Upvotes: 1

Related Questions