【问题标题】:Python program freezes and closes when entering an input?输入输入时Python程序冻结并关闭?
【发布时间】:2017-04-06 19:11:53
【问题描述】:

我目前正在编写一个程序,它绘制一个多项式并使用辛普森的 3/8 规则对两个端点之间的曲线下的区域进行着色,然后在图表上打印该信息。目前,该程序适用于两个端点(2 和 9)之间的一个多项式(“(x - 3) * (x - 5) * (x - 7) + 85”)。但是,当尝试使用 input 命令让程序接受多项式或任一端点的输入时,程序会冻结并崩溃,而不会构建图形。即使重新输入当前号码也会发生这种情况。下面是代码:

这是代码的基础

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)

这里我打印了曲线下的面积,根据辛普森的 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(input("enter your endpoints in the format 2,9")) # integral limits' 时,程序 errors out as shown.

任何帮助将不胜感激。我很难理解这个困境,所以我很抱歉没有提供更多信息。

【问题讨论】:

    标签: python numpy matplotlib anaconda freeze


    【解决方案1】:

    这是运行时系统中的一个错误,它不会给您错误消息。崩溃很少是可接受的响应。

    我怀疑直接原因是您的输入转换无效: int 接受一个字符串参数,表示单个整数。当您尝试将其分配给 两个 变量时,您应该收到一条消息,告诉您没有足够的值可以解压...但首先,您会得到尝试将“2,9”等字符串转换为单个整数的 ValueError。

    试试这个吧:

    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]
    

    您可以添加错误检查或将其折叠到一行 - 但我希望您现在可以看到所需的处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 2022-01-24
      • 1970-01-01
      • 2015-03-21
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      相关资源
      最近更新 更多