Raw_Input
Raw_Input

Reputation: 401

Python Float Lost with Big Numbers

I am working with some large numbers and have run into a problem with lost floating values.

When multiplying large numbers, the float portion seems to go missing, lost, becomes zero. When using the same code with smaller numbers, this does not happen.

Trivial example:

import math
f_ProNum(31 * 61) ## Correct: DEBUG float: 314.833333
f_ProNum(5915587277 * 3367900313) ## Incorrect: DEBUG float: 3320518040297852928.000000

def f_ProNum(v_Num):
    """Syntax: (int); Returns: (float)"""
    print("DEBUG float: %f") %((v_Num - 2.0)/6.0) # DEBUG
    v_PDNum = (v_Num - 2.0)/6.0
    return v_PDNum

As seen in the second call, the float seems to get lost, or set to zero.

Why is it doing this, and how may it be addressed, fixed?

Upvotes: 2

Views: 735

Answers (1)

ech
ech

Reputation: 138

Larger float values lose precision. To simplify a bit, floats have a fixed number of "digits" that are used, called the mantissa or significand, so large enough numbers are essentially going to use all their digits on the part to the left of the decimal place. For more see: https://en.wikipedia.org/wiki/Floating_point#Internal_representation

To solve your problem, you might try using the decimal module, which allows you to configure the precision you need: https://docs.python.org/2/library/decimal.html

Upvotes: 4

Related Questions