sympy的plot_parametric显示TypeError:无法转换复杂

2024-10-02 10:29:36 发布

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

我想画一条实际上是S形的曲线:

  1. 画一个圆
  2. 将半圆形的下半部分移动一整直径距离

但是代码显示TypeError: can't convert complex to float。复数在哪里?如何修复?谢谢

import sympy as sp
from sympy.plotting import *

u = sp.Symbol('u', real=True)
R0 = 2
boundLower = 0
boundUpper = 2 * sp.pi

x_u = sp.Piecewise(
    (R0*sp.cos(u)+R0, sp.And(boundLower <= u, u <= boundUpper/2)),
    (R0*sp.cos(u)+3*R0, sp.And(boundUpper/2 < u, u <= boundUpper)),
)

y_u = sp.Piecewise(
    (R0*sp.sin(u), sp.And(boundLower <= u,  u <= boundUpper/2)),
    (R0*sp.sin(u), sp.And(boundUpper/2 < u, u <= boundUpper)),
)

plot_parametric(x_u, y_u, (u, boundLower, boundUpper))

Tags: and代码import距离sincos曲线sp
1条回答
网友
1楼 · 发布于 2024-10-02 10:29:36

SymPy的plot涉及一些容易出错的操作,旨在提高绘图的性能;它们涉及complex数据类型,当涉及不等式时,有时会导致错误。在这种情况下,减少不平等的数量有助于:

x_u = sp.Piecewise(
    (R0*sp.cos(u)+R0, u <= boundUpper/2),
    (R0*sp.cos(u)+3*R0, u <= boundUpper),
)

y_u = sp.Piecewise(
    (R0*sp.sin(u), u <= boundUpper/2),
    (R0*sp.sin(u), u <= boundUpper),
)

plot_parametric(x_u, y_u, (u, boundLower, boundUpper))

上面是分段在SymPy中通常是如何表示的:条件按给定的顺序进行求值,第一个条件为真的条件将得到相应表达式的求值结果。(顺便说一下,u <= boundUpper可以被True代替。)结果:

piecewise

这仍然不理想。当然,从0到4的水平线不应该在那里——这是一个绘图的人工制品。同时,显示此代码

UserWarning: The evaluation of the expression is problematic. We are trying a failback method that may still work. Please report this as a bug.

我建议避免分片策划。相反,使用extend组合一个片段的绘图,如下所示。在

^{pr2}$

输出(无警告和工件)。在

better

相关问题 更多 >

    热门问题