python - why is my function not always returning the correct list? -
i have function takes 2 inputs, , return array of tuples 2 numbers in given tuple have exact same ratio 2 numbers given function!
so working fine, reason in instances, not picking every tuple. here example of it, , don't know why:
in [52]: def find_r(num1,num2): ....: ratio = num1/float(num2) ....: ratio = 1/ratio ....: my_list = [(a,int(a * ratio)) in range(1,num1) if float(a * ratio).is_integer()] #and * 1/float(ratio) + <= num1] ....: return my_list ....: in [53]: find_r(100,364) out[53]: [(75, 273)]
so returned 1 tuple, if divide both 75 , 273 3, tuple of 25 , 91, have same ratio! why did function not pick instance?
if helps, suspect has is_integer()
method, not sure.
thanks!
it due imprecision of floating point arithmetic:
>>> ((100/364)*364).is_integer() false >>> ((25/91)*91).is_integer() false
instead of doing you're doing, should check equivalence of fractions cross-multiplying. is, given fraction a/b
, check if equivalent c/d
, check whether ad == bc
. avoid division , keep integers.
you can this:
def find_r(num1,num2): return [(a, a*num2//num1) in range(1, num1) if (a*num2) % num1 == 0] >>> find_r(100, 364) [(25, 91), (50, 182), (75, 273)]
(there other ways accomplish task, similar original approach.)
Comments
Post a Comment