Thursday, May 1, 2008

How the Decimal is in Python

In python,if you type this:
>>0.1+0.1+0.1-0.3
you will get
>>5.5511151231257827e-017
The reason is cause of your hardware.Then how should we do then we can get a zero?Use Decimal,
>>from decimal import Decimal
>>Decimal(0.1)+Decimal(0.1)+Decimal(0.1)-Decimal(0.3)
>>Decimal(0)
Great,isn't it?
Then consider another condition,if this:
>>1/3
>>0.33333331
but sometime for example we only want to got fist four precision,how to do it?
>>decimal.getcontext().prec=4
>>Decimal(1)/Decimal(3)
Decimal(0.3333)

Wow...fantastic:)

No comments: