Elvez The Elf
Elvez The Elf

Reputation: 97

Python, How long decimal point can a float have?

I made a pi calculator. But it just corrects first 7 decimal points and starts returning the same results. By the look of the things it is about my float values getting bigger because I use a limit. But is there a limit for decimal numbers in python? I read some documents but there are numbers with even 100 decimal points but I can just get to 11.

My code:

import math
import decimal
import datetime

sqrtt=1.
sumn=0.
tryc=0
outerrepeat=1000000000
while outerrepeat>0:
    tryc+=1
    repeat=10000000
    a=datetime.datetime.now()
    print "\n>>>Processing...\n"
    while repeat>0:

        sumn+=1/(sqrtt**2)
        sqrtt+=1
        repeat-=1
    b=datetime.datetime.now()
    print ">>>Process complete.\n"
    print ">>>Calculate time: "+str(b-a) + " Try-" + str(tryc) +" "+      str(math.sqrt(sumn*6)) + "\n"
    outerrepeat-=1


print "\nThis is all I can do."

May help: Running on IDLE. Calculation is done by basel problem. Always gets stuck at 3.14159264498. Also never gets further than 11 decimal points but sometimes gets lower. Should say that my limit (sqrtt) hits 8th power of 10 (Maybe lower but higher than 7th power of 10.) Thanks.

Upvotes: 1

Views: 5386

Answers (3)

FHTMitchell
FHTMitchell

Reputation: 12157

Python uses 64 bit floats which have 15 to 17 decimal digits of precision.

Proof can be found here where we can see the python float value is stored as a C double (which is almost always a 64 bit floating point number).

typedef struct {
    PyObject_HEAD
    double ob_fval;  // this is the actual float value
} PyFloatObject;

You can use the decimal.Decimal object for infinite precision.

An example with calculating e

import decimal
import math

decimal.getcontext().prec = 100  # set the precision, can be as large as you like

e = decimal.Decimal(0)
next_e = decimal.Decimal('NaN')  # init as not a number
i = 0

while e != next_e:
    e, next_e = next_e, e + decimal.Decimal(1) / math.factorial(i)
    i += 1


e #--> Decimal('2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166428')

Upvotes: 1

Superluminal
Superluminal

Reputation: 977

Also very useful will be this tutorial. Floating Point Arithmetic: Issues and Limitations

The precision of python floats is bordered to 17 digits. "On a typical machine running Python, there are 53 bits of precision available for a Python float". Its not only python, it is a standart. So it is useful to be familiar with.

Upvotes: 0

Håken Lid
Håken Lid

Reputation: 23064

With a typical python implementation, floats are 64 bits, with 53 bits of precision. That's 15 to 17 significant decimal digits.

https://en.wikipedia.org/wiki/Double-precision_floating-point_format

Upvotes: 1

Related Questions