0

something is wrong with my while loop inside my eval_strfrac(s, base=2) function. for 3.14 base 10 it is very close,for 100.101 base 2 it is way off.Thanks!

#TEST to validate 
def is_valid_strfrac(s, base=2):
    return all([is_valid_strdigit(c, base) for c in s if c != '.']) \
        and (len([c for c in s if c == '.']) <= 1)

def eval_strfrac(s, base=2):
    assert is_valid_strfrac(s, base), "'{}' contains invalid digits for a base-{} number.".format(s, base)

    #
    predot,postdot = s.split('.')
    whole = eval_strint(predot,bse)
    whole = int(predot,base)
    postlist = [int(p) for p in postdot]
    print(postlist)
    i = 0
    while i <= len(postlist):
        yo = (postlist[i])*((float(base))**-(float(i + 1)))
        yo += yo
        i +=1
        return float(whole) + float(yo)


#### Test 0: `eval_strfrac_test0`#####

def check_eval_strfrac(s, v_true, base=2, tol=1e-7):
    v_you = eval_strfrac(s, base)
    assert type(v_you) is float, "Your function did not return a `float` as instructed."
    delta_v = v_you - v_true
    msg = "[{}]_{{{}}} ~= {}: You computed {}, which differs by {}.".format(s, base, v_true,
                                                                            v_you, delta_v)
    print(msg)
    assert abs(delta_v) <= tol, "Difference exceeds expected tolerance."

# Test cases from the video
check_eval_strfrac('3.14', 3.14, base=10)
check_eval_strfrac('100.101', 4.625, base=2)
check_eval_strfrac('11.0010001111', 3.1396484375, base=2)

# A hex test case
check_eval_strfrac('f.a', 15.625, base=16)

print("\n(Passed!)")

[3.14]_{10} ~= 3.14: You computed 3.2, which differs by 0.06000000000000005.

[100.101]_{2} ~= 4.625: You computed 5.0, which differs by 0.375.

1 Answer 1

1

In the while loop, yo = (postlist[i])*((float(base))**-(float(i + 1))) calculates the value of one digit. Then yo += yo doubles it. Instead, you should be adding the values of digits to an accumulating sum.

Two lines later, return float(whole) + float(yo) returns from the function from inside the loop, so only one iteration of the loop is performed. The return should be after and outside the loop (not indented with the code inside the loop).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.