私は現在、多項式をグラフ化し、Simpsonの3/8のルールを使って2つの端点の間の曲線の下の領域を陰にし、その情報をグラフに印刷するプログラムを作成しています。現在、プログラムは2つの端点(2と9)の間の1つの多項式( "(x - 3)*(x - 5)*(x - 7)+ 85")に対して正しく機能します。しかし、プログラムが入力コマンドを使用して多項式またはいずれかの端点の入力を受け入れるようにしようとすると、プログラムはフリーズし、グラフを作成せずにクラッシュします。これは、現在の番号が再入力された場合でも発生します。ここ入力時にPythonプログラムがフリーズして終了しますか?
コード
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
の塩基である。ここでIは、多項式はFUNCであると定義する。ここで(X)
def func(x):
return (x - 3) * (x - 5) * (x - 7) + 85
Iが計算するれる関数を定義する:以下のコードでありますシンプソン
ここdef simpson(function, a, b, n):
"""Approximates the definite integral of f from a to b by the
composite Simpson's rule, using n subintervals (with n even)"""
if n % 2:
raise ValueError("n must be even (received n=%d)" % n)
h = (b - a)/n #The first section of Simpson's 3/8ths rule
s = function(a) + function(b) #The addition of functions over an interval
for i in range(1, n, 2):
s += 4 * function(a + i * h)
for i in range(2, n-1, 2):
s += 2 * function(a + i * h)
return(s * h/3)
を使用して曲線下面積、私はINTEGへの間のエンドポイントを定義しますレート
a, b = 2, 9 # integral limits
ここでは私がグラフ
plt.text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$",
horizontalalignment='center', fontsize=20)
に積分表記を印刷斜線領域ここ
# Make the shaded region
ix = np.linspace(a, b)
iy = func(ix)
verts = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)]
poly = Polygon(verts, facecolor='0.9', edgecolor='0.5')
ax.add_patch(poly)
を構築便宜
x = np.linspace(0, 10) #Generates 100 points evenly spaced between 0 and 10
y = func(x) #Just defines y to be f(x) so its ez later on
fig, ax = plt.subplots()
plt.plot(x, y, 'r', linewidth=2)
plt.ylim(ymin=0)
final_integral = simpson(lambda t:func(t), a, b, 100000)
ここ
ためのさらにいくつかの定義であります
ここでは印刷しますグラフ
ここax.text(0.25, 135, r"Using Simpson's 3/8ths rule, the area under the curve is: ", fontsize=20) #r denotes a raw string
ax.text(0.25, 114, final_integral , fontsize=20) #prints the value of the
integral defined using simpson's 3/8ths prior
にシンプソンの3/8thsルールによって計算された曲線下面積、私はエンドポイントが読み取ることが規定されている行を変更したときに、私は、しかし、グラフ
plt.figtext(0.9, 0.05, '$x$')
plt.figtext(0.1, 0.9, '$y$')
ax.spines['right'].set_visible(False) #no dashes on axis
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.set_xticks((a, b))
ax.set_xticklabels(('$a$', '$b$'))
ax.set_yticks([])
plt.show()
を構築終えます'a、b = int(入力( "エンドポイントをフォーマット2,9")で入力する)#積分限界'、プログラムerrors out as shown.
助けていただければ幸いです。私はジレンマを理解するのに苦労しているので、私はもっと情報を提供しないためにappoligize。