[Tutor] Rounding to n significant digits
Sander Sweers
sander.sweers at gmail.com
Wed Sep 2 13:19:33 CEST 2009
2009/9/2 Alan Gauld <alan.gauld at btinternet.com>:
> That having been said the two approaches, string or math, are equally
> valid. I suspect the math version will be much slower since it calls
> several functions but I haven't timed it.
>
>>> def round_to_n(x, n):
>>> fmt = "%%.%de" % (n)
>>> return float( fmt % x)
>>
>>> import math
>>>
>>> def round_figures(x, n):
>>> return round(x, int(n - math.ceil(math.log10(abs(x)))))
Maybe the decimal module can help out. It can limit precision to n
digits globally and per instance. I might be way of here so please do
not hesitate to correct me :-)
>>> i = float(1.333333)
>>> i
1.3333330000000001
>>> c = decimal.getcontext().copy()
>>> c.prec = 2
>>> d = c.create_decimal(str(i))
>>> d
Decimal('1.3')
>>> x = 2
>>> x < d
False
>>> x > d
True
Greets
Sander
More information about the Tutor
mailing list