pythonで二分法を使って平方根を計算し、ついでに図に示すプログラムを組んでいます。
標準入力から任意の値を入れて計算するのが条件ですが、なぜか以下のようなメッセージが出てしまいます。標準入力の位置が悪いのでしょうか?
#自作のコード
from matplotlib import pyplot as plt def f(b,x): return x**2-b def df(b,x): return 2*x h=1e-6 return (f(b,x+h)-f(b,x))/h b=int(input("任意の整数の平方根を計算します:")) x=[i/10 for i in range(b)] y=[f(b,w) for w in x] plt.plot(x,y) while True: xnew=x-f(b,x)/df(b,x) if abs(xnew-x)<1e-6: break x=xnew plt.plot([0,x],[0,0]) plt.plot(x,f(b,x),"or") plt.show() print("sqrt({})={}".format(b,x))
#エラーメッセージ
TypeError Traceback (most recent call last) <ipython-input-18-a301208efa0c> in <module>() 14 plt.plot(x,y) 15 while True: ---> 16 xnew=x-f(b,x)/df(b,x) 17 if abs(xnew-x)<1e-6: 18 break <ipython-input-18-a301208efa0c> in f(b, x) 4 from matplotlib import pyplot as plt 5 def f(b,x): ----> 6 return x**2-b 7 def df(b,x): 8 return 2*x TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'