2017-04-06 51 views
1

我目前正在編寫一個程序,它使用辛普森的3/8規則繪製多項式圖形並對兩個端點之間的曲線下面的區域進行着色,然後將該信息打印在圖上。目前,程序在兩個端點(2和9)之間對於一個多項式(「(x-3)*(x-5)*(x-7)+85」)正常工作。但是,當試圖讓程序接受多項式的輸入或使用輸入命令的任一端點時,程序會凍結並崩潰,而不會構建圖形。即使當前的數字重新輸入,也會發生這種情況。下面是代碼:Python程序在輸入輸入時凍結並關閉?

這裏是代碼

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib.patches import Polygon 

在這裏,我定義多項式爲FUNC(X)

def func(x): 
    return (x - 3) * (x - 5) * (x - 7) + 85 

在這裏,我定義與要計算其功能的基礎使用辛普森規則的曲線下面積

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) 

在這裏我定義了要在其間整合的端點率

a, b = 2, 9 # integral limits 

這裏是爲了方便

幾個定義
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) 

在這裏,我構建了陰影區域

# 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) 

這裏我打印圖形上的積分符號

plt.text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$", 
    horizontalalignment='center', fontsize=20) 

這裏我打印如用Simpson 3/3/8計算出的曲線下的面積在圖上排除

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 

在這裏,我完成構建圖形

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.

任何幫助,將不勝感激。我正在努力理解這種困境,所以我喜歡不提供更多信息。

回答

1

這是運行時系統中的一個錯誤,因爲它不會給你一個錯誤信息。碰撞很少是可以接受的答案。

我懷疑最近的原因是你的無效輸入轉換:int接受一個字符串參數與一個整數表示。當您嘗試將此分配給兩個變量時,您的應該會收到一條消息,告訴您沒有足夠的值來解壓縮,但首先,您將得到一個ValueError,用於嘗試將字符串轉換爲「2,9」變成一個整數。

試試這個,而是:

str_in = input("enter your endpoints in the format 2,9") # integral limits 
fields = str_in.split(',') 
a, b = [int(i) for i in fields] 

您可以添加錯誤檢查或崩潰這一條線 - 但是我希望你可以看到現在所需要的處理。