A little more: decimal_portion

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Oct 4 17:46:03 CEST 2014


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".



-- 
Steven




More information about the Python-list mailing list