我试图绘制一个复数函数,但我有一些问题(我通常不使用matplotlib,因此可能是一个非常愚蠢的错误)。首先,我创建了一个函数来解析给定数学函数的真实和复杂部分(n是函数索引,x是变量):
import parser
def e_parser( real_part, imaginary_part, n, x ): 
    real_p = parser.expr( real_part ).compile()
    imag_p = parser.expr( imaginary_part ).compile()
    
    return complex( eval( real_p ), eval( imag_p ) )它工作得很完美。现在,我创建了另一个函数来绘制解析的复杂数学函数:
import numpy as np
import matplotlib.pyplot as plt
def plotter( real_part, imaginary_part, a, b, n ):   
    x = np.arange( a, b, ( ( a-b ) / 10 ) )
    
    def func( x ):
        return e_parser( real_part, imaginary_part, n, x )
    my_label = "Wave-function for n = " + str( n )
    
    plt.xlabel( "re" )
    plt.ylabel( "im" )
    plt.plot( np.real( func( x ) ), np.imag( func( x ) ), label = my_label )
    plt.legend()
    plt.show()我在一个演示程序中尝试过这个:
import numpy as np
plotter( "np.sin(n*np.pi*x)", "x", 0, 1, 3 )但产出如下:
Traceback (most recent call last):
  File "main.py", line 130, in <module>
    main()
  File "main.py", line 21, in main
    ft.plotter( "np.sin(n*np.pi*x)", "x", 0, 1, 3 )
  File "/home/gianluca/WaveNCC/src/functions.py", line 208, in plotter
    plt.plot( np.real( func( x ) ), np.imag( func( x ) ), label = my_label )
  File "/home/gianluca/WaveNCC/src/functions.py", line 202, in func
    return ut.e_parser( real_part, imaginary_part, n, x )
  File "/home/gianluca/WaveNCC/src/utils.py", line 208, in e_parser
    return complex( eval( real_p ), eval( imag_p ) )
  File "<syntax-tree>", line 1, in <module>
TypeError: only size-1 arrays can be converted to Python scalars如果我试图绘制相同的函数,但将虚设部分设置为0:
Traceback (most recent call last):
  File "main.py", line 130, in <module>
    main()
  File "main.py", line 21, in main
    ft.plotter( "np.sin(n*np.pi*x)", 0, 0, 1, 3 )
  File "/home/gianluca/WaveNCC/src/functions.py", line 211, in plotter
    plt = cp.plot(
  File "/home/gianluca/.local/lib/python3.8/site-packages/cplot/_main.py", line 265, in plot
    extent = (x_range[0], x_range[1], y_range[0], y_range[1])
TypeError: 'int' object is not subscriptable你知道发生了什么事吗?谢谢。
发布于 2022-02-02 08:52:45
complex只能将标量作为参数,而不能将数组作为参数。所以你应该用
return eval( real_p ) +  eval( imag_p )  * 1j而不是
return complex( eval( real_p ), eval( imag_p ) )(而且,您当然打算编写x = np.arange( a, b, ( ( b-a ) / 10 ) )而不是x = np.arange( a, b, ( ( a-b ) / 10 ) ))
https://stackoverflow.com/questions/70952362
复制相似问题