x<0の場合も含めた、任意の実数値xに対して、三乗根の近似値を求めるコードを完成させるという問題なのですが、自分の書いたプログラムだと負の数の三乗根が求められません。
恐らく、探索区間が違うと思うのですが、どこが間違っているのでしょうか。
def cube_root_bisection_full_range(cube): pass epsilon = 0.000000001 count_guesses = 0 #探索区間の上限と下限(初期値 (0、cube)) low =0.0 if cube >= 1: high = cube else: high = 1 low < 0.0 if cube >= 1: high = cube else: high < 1 guess = (low + high)/2 while abs(guess**3 - cube) >= epsilon : if guess**3 < cube: low = guess else: high = guess guess = (low + high)/2 count_guesses += 1 if count_guesses >1e6: print(f'FAIL: cannot reach the cube root {cube}') break print(' count_guess =', count_guesses ) if abs(guess**3 - cube) < epsilon: print(guess, 'is close to the cube root of ',cube) print(f'verify: {guess}**3 =',guess**3 ) print('') cube_root_bisection_full_range(0.1) cube_root_bisection_full_range(-0.5) cube_root_bisection_full_range(-2) cube_root_bisection_full_range(5)
【結果】
count_guess = 28
0.464158883318305 is close to the cube root of 0.1
verify: 0.464158883318305**3 = 0.09999999997222532
FAIL: cannot reach the cube root -0.5
count_guess = 1000001
FAIL: cannot reach the cube root -2
count_guess = 1000001
count_guess = 32
1.7099759465781972 is close to the cube root of 5
verify: 1.7099759465781972**3 = 4.999999999135954
回答1件
あなたの回答
tips
プレビュー