A little more: decimal_portion

wxjmfauth at gmail.com wxjmfauth at gmail.com
Sun Oct 5 09:14:59 CEST 2014


Le samedi 4 octobre 2014 18:13:27 UTC+2, Seymore4Head a écrit :
> On Sun, 05 Oct 2014 01:46:03 +1000, Steven D'Aprano
> 
> <steve+comp.lang.python at pearwood.info> wrote:
> 
> 
> 
> >Seymore4Head wrote:
> 
> >
> 
> >>  A little more: decimal_portion
> 
> >> 
> 
> >> Write a function that takes two number parameters and returns a float
> 
> >> that is the decimal portion of the result of dividing the first
> 
> >> parameter by the second. (For example, if the parameters are 5 and 2,
> 
> >> the result of 5/2 is 2.5, so the return value would be 0.5)
> 
> >> 
> 
> >> http://imgur.com/a0Csi43
> 
> >> 
> 
> >> def decimal_portion(a,b):
> 
> >>     return float((b/a)-((b//a)))
> 
> >> 
> 
> >> print (decimal_portion(5,2))
> 
> >> 
> 
> >> I get 0.4 and the answer is supposed to be 0.5.
> 
> >
> 
> >Hint: given arguments a=5, b=2, you want 5/2. What do you calculate? Look at
> 
> >the order of the arguments a and b in the function def line, and in the
> 
> >calculations you perform.
> 
> >
> 
> >Once you fix that, I can suggest a more efficient way of calculating the
> 
> >answer: use the modulo operator %
> 
> >
> 
> >Given arguments 5 and 2, you want 0.5 == 1/2, and 5%2 returns 1.
> 
> >
> 
> >Given arguments 6 and 2, you want 0.0 == 0/2, and 6%2 returns 0.
> 
> >
> 
> >Given arguments 8 and 3, you want 0.6666... == 2/3, and 8%3 returns 2.
> 
> >
> 
> >
> 
> >P.S. the usual name for this function is "fraction part", sometimes "fp".
> 
> 
> 
> Yeah, I caught my mistake.  Thanks for the suggestions.
> 
> I was expecting a lesson in rounding errors, so I had ruled out the
> 
> error was on my part.  (Something I should never do)

%%%%%

>>> # hints
>>> a = 5 / 2
>>> a - floor(a)
0.5
>>> 
>>> import math
>>> math.modf(a)
(0.5, 2.0)
>>> math.modf(pi)
(0.14159265358979312, 3.0)
>>>



More information about the Python-list mailing list