在Python中,如何以矢量化的方式而不是在循环中计算值数组?

2024-03-29 09:59:42 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是:

编写并测试一个Python脚本,该脚本接受来自输入的指数n的最多5个值的列表,并在同一个图上绘制y=1/(x^n+1)的曲线。这个程序应该为x,y,u,1,…,创建一个NumPy数组。。。最多y_4个值。x坐标数组应包含201个均匀分布的值,介于-10和10之间(包括-10和10)。您应该通过对x执行矢量化操作来计算y值(不要在循环中一次计算一个y值)。在一个蓝色的图形上绘制y_0与x的关系图,并用红色、绿色、青色和洋红在同一个图形上绘制y_1(等等)与x的关系。您应该沿着x、y轴和网格的轴标签在绘图上添加标题。准备好后,请记住使用show()函数

不带参数的show()命令将暂停代码执行。程序应该在屏幕上打印一条消息,提醒用户关闭绘图窗口,程序才能继续运行。一旦用户关闭图形,您的程序应该返回并允许用户为n输入另一个值序列。程序应接受n的任何浮点值,并在输入“q”作为第一个值时终止。如果输入“q”作为第二个、第三个、第四个或第五个值,程序应仅生成这些值的绘图(例如,如果输入2、4、6、q,则程序应生成一个只有三条曲线的绘图,即蓝色、红色和绿色,然后返回以获取更多输入)。在那里,用户应该再次输入一个指示所有输入的n值。(提示:在尝试将输入字符串转换为float之前,如果float转换不起作用,可以使用except子句将输入字符串转换为float,以防float转换不起作用)。运行你的程序,n=2,4,8,'fred',16,32,(这应该会产生一个图),然后n=2,4,9,和,q,(这应该会产生另一个图。。。可能会出现一个关于除以0…,然后“q”终止的运行时警告。在

输出应该看起来像下面这样。注意titlexlabelylabelpyplot命令接受可以使用format方法将变量合并到字符串中的字符串。在

Enter exponent n (q to quit)>2
Enter exponent n (q to quit)>4
Enter exponent n (q to quit)>8
Enter exponent n (q to quit)>fred
That's not a number!!!
Enter exponent n (q to quit)>16
Enter exponent n (q to quit)>32
Close plot window to continue...

Image for the above input

^{pr2}$

Image for above output

^{3}$

我的代码是:

import numpy as np
import matplotlib.pyplot as mplt
import sys
while True:
    try:
        n_list = []
        for i in range(5):
            exponent = input('Enter exponent n (q to quit)>')
            n_list.insert(i,float(exponent))
    except ValueError:
        if exponent == 'q' and i == 0:
            sys.exit()
        elif exponent == 'q' and i != 0:
            break
        else:
            print('That\'s not a number!!!')
            for j in range(i,5):
                exponent = input('Enter exponent n (q to quit)>')
                n_list.insert(j,float(exponent))
    finally:
        if exponent == 'q' and i == 0:
            sys.exit()
        print(n_list)
        x = np.linspace(-10,10,num=201)
        y1 = 1/((x**n_list[0])+1)
        y2 = 1/((x**n_list[1])+1)
        y3 = 1/((x**n_list[2])+1)
        y4 = 1/((x**n_list[3])+1)
        y5 = 1/((x**n_list[4])+1)
        mplt.plot(x,y1,'b-')
        mplt.plot(x,y2,'r-')
        mplt.plot(x,y3,'g-')
        mplt.plot(x,y4,'c-')
        mplt.plot(x,y5,'m-')
        mplt.title('$1/(x^n+1)$, n={}'.format(n_list))
        mplt.xlabel('x')
        mplt.ylabel('f(x)')
        mplt.grid(True)
        print('Close plot window to continue...')
        mplt.show()

我的输出是:

Enter exponent n (q to quit)>2
Enter exponent n (q to quit)>4
Enter exponent n (q to quit)>8
Enter exponent n (q to quit)>fred
That's not a number!!!
Enter exponent n (q to quit)>16
Enter exponent n (q to quit)>32

当我把我的输出作为:

Enter exponent n (q to quit)>2
Enter exponent n (q to quit)>4
Enter exponent n (q to quit)>9
Enter exponent n (q to quit)>q
That's not a number
Enter exponent n (q to quit)>

问题是,在第一次输入之后,程序在输入q之后并没有退出。当输入2,4,9,q时,有人能解释一下第二部分的逻辑吗?还有另一种方法可以计算y值吗?在

提前谢谢!!在


Tags: to字符串用户程序绘图numberthatplot
1条回答
网友
1楼 · 发布于 2024-03-29 09:59:42

实际上,我没有您提到的问题,但是在第二种情况下,它无法为i==3和{}创建绘图,因为没有这样的列表元素。在

我已经尝试过了,因为我喜欢清晰的函数编程风格,所以我创建了一个小脚本来满足您的需求。(最初我尝试过你的解决方案,但我总是偶然发现一些错误,最后只是尝试自己实现它)。我希望这些评论能传达我为什么要这样做:

import numpy as np
import matplotlib.pyplot as mplt
import sys

def getinput():
    n_list = []
    # Use a while loop instead of a for loop
    while len(n_list) < 5:

        # Get some number
        exponent = input('Enter exponent n (q to quit)>')

        # This will fail with a ValueError if it cannot be converted to float
        try:
            n_list.append(float(exponent))

        # Never use bare except statements!
        except ValueError:
            if exponent == 'q':
                if n_list:
                    # empty lists evaluate to False so we have some elements
                    # Returning them breaks the loop and exits the function
                    return n_list
                else:
                    # We had no elements in the list so just exit
                    sys.exit()
            # It wasn't q so it was a bad input
            else:
                print('That is not a number!!!')
    return n_list

def plotthem(n_list):
    x = np.linspace(-10,10,num=201)
    style = ['b-', 'r-', 'g-', 'c-','m-']
    # Only plot as many lines as there are objects in the list (and use the appropriate style)
    for i in range(len(n_list)):
        mplt.plot(x, 1/((x**n_list[i])+1), style[i])
    mplt.title('$1/(x^n+1)$, n={}'.format(n_list))
    mplt.xlabel('x')
    mplt.ylabel('f(x)')
    mplt.grid(True)
    print('Close plot window to continue...')
    mplt.show()

# If started as script
if __name__ == "__main__":
    while True:
        plotthem(getinput())

要在完全矢量化的解决方案中计算结果函数,可以用以下方法替换它们:

^{pr2}$

相关问题 更多 >