Home > Software design >  Python function doesn't return any values
Python function doesn't return any values

Time:05-16

It works with certain values (e.g "100 12 2"), but fails at "102 12 2" for some reason. Checked both on Windows and MacOS with different python versions, results are the same and are not affected by setup.

from math import floor

s, x, y = 102, 12, 2

def calc(s, x, y):
    q = 0
    if x > y:
        while s - (s / x) > 0:
            q  = s / x
            q1 = s / x
            s = s - (s / x) * x
            s  = q1 * y
        return floor(q)
    else:
        return 'Inf'

if type(calc(s, x, y)) is int:
    print(calc(s, x, y))
else:
    print('Inf')

CodePudding user response:

Try replacing the zero in the condition with a small number, such as 1e-16:

from math import floor

s, x, y = 102, 12, 2

def calc(s, x, y):
    q = 0
    if x > y:
        while s - (s / x) > 1e-16:
            q  = s / x
            q1 = s / x
            s = s - (s / x) * x
            s  = q1 * y
        return floor(q)
    else:
        return float('Inf')

print(calc(s, x, y)) # 10

The reason of doing so is that the sequence s - s/x does not become exactly zero; it only gets arbitrarily close to zero. (Even if exact zero is guaranteed algebraically, float is subject to inherent imprecision, so you need some threshold anyways.)

  • Related