really small values

mensanator at aol.com mensanator at aol.com
Fri Jul 20 00:45:02 EDT 2007


On Jul 19, 5:11?pm, Zentrader <zentrad... at gmail.com> wrote:
> On Jul 17, 2:13 pm, "Dee Asbury" <deeasb... at msn.com> wrote:
>
> > In multiplying a value of xe^-325 with ye^-4, Python is returning zero. How
> > do I get it to give me back my tiny value?
>
> > Thanks!
> > Dee
>
> Also, Python's decimal class allows theoretically unlimited
> precision.  I have extremely limited knowledge here.  It gives the
> following for 2**-325.  I have no idea if the answer is correct.

Looks ok, you should get about 0.3 as many decimal digits as bits.

> You'll have to see if gmpy or decimal works better for this.  One
> piece of advice is to use whichever exclusively.  If you use a float
> and then covert to either one, the result will be corrupted.
> import decimal
> decimal.getcontext().prec = 375      ## set precision at 375
> print "2**-325 =", decimal.Decimal(str(2**-325))
>
> 2**-325 = 1.46302386084E-98

Interestingly, using str() causes you to lose precision.
>>> a = 2**-325
>>> a
1.463023860841312e-098
>>> b = str(a)
>>> b
'1.46302386084e-098'

Setting the precision to 375 didn't help because you
corrupted the value before you converted it to decimal.

Although the 375 will allow you to do this:

>>> a = decimal.Decimal('1e-325')
>>> b = decimal.Decimal('1e-4')
>>> a
Decimal("1E-325")
>>> b
Decimal("0.0001")
>>> a+b
Decimal("0.0001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001")


You can also do this in gmpy, although you set precision in bits, not
decimal digits.






More information about the Python-list mailing list