import math
def my_f(x):
return math.sqrt(x)+1
関数を使ってみます。
my_f(4)
指定される区間[a,b]におけるグラフを描くために、[a,b]の分割を考え、x_listを作成します。
#関数の引数は不定なので、コードを準備するために、具体的な値でためしないとコードを書きにくいです。
#とりあえず、a=1,b=10とします。実際の計算では、aとbの値は引数の値をとります。
a=1
b=10
h=(b-a)/100; #区間[a,b]の100分割を考えます。
n_list = range(0,101)
x_list = []
for n in n_list:
x_list.append(a + n*h)
print(x_list)
グラフの描画に必要となる y_listを作成します。x_listとy_listを使って、グラフを作成してみます。
#y_listを作成します。
y_list=[]
for x in x_list:
y=my_f(x)
y_list.append(y)
#x_list,y_listのグラフを作成します。
import matplotlib.pyplot as plt
plt.plot(x_list, y_list,'b-')
plt.grid()
plt.show()
Step 4.
上記のコードをdraw_graph(a,b)にまとめます。特に、a,bは引数から値を取るので、関数の中でa,bの具体的な値を設定する必要はないです。
import matplotlib.pyplot as plt
import math
def my_f(x):
return math.sqrt(x)+1
def draw_f(a,b):
#x_listを作成します。
h=(b-a)/100; #区間[a,b]の100分割を考えます。
n_list = range(0,101)
x_list = []
for n in n_list:
x_list.append(a + n*h)
#y_listを作成します。
y_list=[]
for x in x_list:
y=my_f(x)
y_list.append(y)
#x_list,y_listのグラフを作成します。
plt.plot(x_list, y_list,'b.')
plt.grid()
plt.show()
他のa,bの値で試してみます。例えば、a=1,b=100。
draw_f(1,100)