George Willcox
George Willcox

Reputation: 673

How to store decimal values as a varible

I'm writing a program that uses an infinite sum to calculate pi to a large number of decimal places very fast, 22 iterations results in 15 decimal places. However, due to limitations of python this is the maximum number of decimal places that can be shown. So try and fix this issue I looked to the internet and found this website that included information on the python decimal class.

This seemed like the perfect solution to my problem, however when trying this method I could not add the numbers and save them to a variable. After going back to the original site to find an answer, I couldn't find anything involving variable. But the page is ludicrously long, and I could have easily missed something.

Here is my code, it works fine with out the decimal part:

from decimal import *
getcontext().prec = 30

n = 0
value = 1 / 2
while True:
    n += 1
    top = 1
    bottom = 2 ** (2 * n + 1) * (2 * n + 1) * 2
    for i in range(n):
        top *= 2 * i + 1
        if i != 0: bottom *= 2 * i + 2

    value += Decimal(top) / Decimal(bottom)
    print(value * 6)

EDIT: This is the error that I have recieved:

TypeError: unsupported operand type(s) for +=: 'float' and 'decimal.Decimal'

This is the first time that I have worked with this class and I am unsure how to contiune.

Upvotes: 0

Views: 3401

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160587

Yes, this is because adding floats to decimals isn't supported, make value (the float) a Decimal first:

value = Decimal(1/2)

The error is explicit in telling you this, saying where the error originated, which operator caused it and what types it got.

Do take a look at the Decimal FAQ provided in the docs for decimal, it has Q's you might be interested in if working with decimals.

Upvotes: 2

Related Questions