Best way to calculate fraction part of x?

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Mar 26 17:59:04 EDT 2015


On 23 March 2015 at 12:52, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> I have a numeric value, possibly a float, Decimal or (improper) Fraction,
> and I want the fractional part. E.g. fract(2.5) should give 0.5.
>
> Here are two ways to do it:
>
> py> x = 2.5
> py> x % 1
> 0.5
> py> x - int(x)
> 0.5
>
> x % 1 is significantly faster, but has the disadvantage of giving the
> complement of the fraction if x is negative:
>
> py> x = -2.75
> py> x % 1
> 0.25

The other version gives -0.75 in this case so I guess that's what you want.

> Are there any other, possibly better, ways to calculate the fractional part
> of a number?

What do you mean by better? Is it just faster?

To modify the % version so that it's equivalent you can do:

>>> x = -2.75
>>> (x % 1) - (x < 0)
-0.75

I'm not sure if that's faster than x - int(x) though. Obviously it
depends which numeric type you're primarily interested in.


Oscar



More information about the Python-list mailing list