Yuzuriha Inori
Yuzuriha Inori

Reputation: 165

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.

Upvotes: 1

Views: 102

Answers (3)

Optionparty
Optionparty

Reputation: 101

My calculator answered -708269172714107481699009991286024451899843951069764894337265485724940929397877002420223612611538343533719511941925009995267129421537088615912195341304356911711190148667675445629255480078613791447051517048459934380810882287658436814218846510469903536007822812720891745018494205080747380297200346292734129604101022854921969160248

Upvotes: 0

Shubham Sharma
Shubham Sharma

Reputation: 71689

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

Upvotes: 3

jcaliz
jcaliz

Reputation: 4021

Another solution can be done using mpmath library which is a library with arbitrary precision

from mpmath import mp, mpf

# set 50 decimal point precision
mp.dps = 50

#...
b=mpf(b)
n=mpf(n)
c=mpf(c)
B = mp((b + (n - b*b) * c))

Output:

mpf('-7.0826917271410749132163115458418859131992983363200556e+326')

Upvotes: 2

Related Questions