Search code examples
pythonpython-3.xlargenumberinfinity

Why -inf when calculation expression that is controlled


I am doing a calculation with variable values:

b=49277625229919252619702799653707265870395898977145078030839752

n=22112825529529666435281085255026230927612089502470015394413748319128822941402001986512729726569746599085900330031400051170742204560859276357953757185954298838958709229238491006703034124620545784566413664540684214361293017694020846391065875914794251435144458199

c=-3.2029790664620333e+67

and the value I am calculating is:

B = (b + (n - b*b) * c)

This returns -inf which should not be, given that I am not constrained by memory space (I have more than 10 gigs where I am doing this).

Is this problem fixable?

Edit : I would also like to know the reason why this is happening so that I can avoid future mishaps.


Solution

  • Your operation returns -inf because it overflows the limit of float. You can use sys.float_info.max to check maximum float value supported by the implementation. Generally this value is 1.7976931348623157e+308. So the numbers above this limit will be represented as float('inf') if positive or float('-inf') if negative.

    Now, in order to solve your problem you can use the builtin decimal library in python.

    Try this:

    from decimal import Decimal
    
    b = Decimal(b)
    n = Decimal(n)
    c = Decimal(c)
    
    B = (b + (n - b*b) * c)
    print(B)
    

    Output:

    -7.082691727141074913216311547E+326