首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么我不能用matplotlib绘制一个复杂的函数(通过解析获得)?

为什么我不能用matplotlib绘制一个复杂的函数(通过解析获得)?
EN

Stack Overflow用户
提问于 2022-02-02 08:19:35
回答 1查看 43关注 0票数 1

我试图绘制一个复数函数,但我有一些问题(我通常不使用matplotlib,因此可能是一个非常愚蠢的错误)。首先,我创建了一个函数来解析给定数学函数的真实和复杂部分(n是函数索引,x是变量):

代码语言:javascript
运行
复制
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 ) )

它工作得很完美。现在,我创建了另一个函数来绘制解析的复杂数学函数:

代码语言:javascript
运行
复制
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()

我在一个演示程序中尝试过这个:

代码语言:javascript
运行
复制
import numpy as np
plotter( "np.sin(n*np.pi*x)", "x", 0, 1, 3 )

但产出如下:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
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

你知道发生了什么事吗?谢谢。

EN

Stack Overflow用户

回答已采纳

发布于 2022-02-02 08:52:45

complex只能将标量作为参数,而不能将数组作为参数。所以你应该用

代码语言:javascript
运行
复制
return eval( real_p ) +  eval( imag_p )  * 1j

而不是

代码语言:javascript
运行
复制
return complex( eval( real_p ), eval( imag_p ) )

(而且,您当然打算编写x = np.arange( a, b, ( ( b-a ) / 10 ) )而不是x = np.arange( a, b, ( ( a-b ) / 10 ) ))

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70952362

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档