[Tutor] decimal precision in python

Steve Willoughby steve at alchemy.com
Mon Feb 6 16:40:29 CET 2012


On 06-Feb-12 07:25, Kapil Shukla wrote:
> i tried writing a small code to calculate option price using the
> binomial tree model. I compared my results with results of the same
> program in excel. There seems to be a minor difference due to decimal
> precision as excel is using 15 decimal precision and python (both 2.7
> and 3.1) using 11. (at least that's what shown on shell)

If you need lots of precision, you might consider using the decimal 
class.  It'll cost you speed vs. the native floating-point type but 
won't cause you round-off errors.

natively, Python uses IEEE double-precision math for all float objects.

For a float value x, instead of just printing it, try this:

print('{0:.30f}'.format(x))

> can some one guide me whats the equivalent of using a double datatype on
> python and i can't use long() in 3.1 any more.

Equivalent to what degree?  Python's float class generally will get you 
where you need to go.  Also the int type automatically extends to 
arbitrary-precision integer values so you don't need explicit "long" 
type anymore.  (Unless I misunderstood your question there.)

> Please also suggest a free editor for python which can at least repeat
> previous command with a key stroke

I use vim, which has that feature.  I suspect any editor worth its salt 
does, or could be programmed to.


-- 
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C


More information about the Tutor mailing list