python - sympy 的plot_parametric 说 TypeError : can't convert complex to float

标签 python plot sympy parametric-equations

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

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

但代码显示TypeError:无法将复数转换为 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))

最佳答案

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 中 Piecewise 的呈现方式:条件按给定的顺序求值,第一个为 True 的结果将导致相应表达式的求值。 (顺便说一句, 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 组合各个片段的图。如下图所示。

x_u1 = R0*sp.cos(u)+R0
x_u2 = R0*sp.cos(u)+3*R0

y_u1 = R0*sp.sin(u)
y_u2 = R0*sp.sin(u)

p = plot_parametric(x_u1, y_u1, (u, boundLower, boundUpper/2), show=False)
p.extend(plot_parametric(x_u2, y_u2, (u, boundUpper/2, boundUpper), show=False))
p.show()

输出(没有警告,也没有工件)。

better

关于python - sympy 的plot_parametric 说 TypeError : can't convert complex to float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52574265/

相关文章:

python - Openpyxl - 如何知道 iter_rows 中的当前行号?

python - scipy.stats.zipf 中的参数是什么意思?

Python Seg Fault 对我来说毫无意义

python - 如何使用 sympy 图的标记参数?

python - matplotlib:多个箱形图的插入轴

python - (-6x^2-x-7)(2x^3+3x^2-2x-5) 作为 SymPy 中的输入

python - 如何在 Django 中编写单元测试

matlab - 如何改变 matlab 图(如颜色图)的线条颜色?

python - 加速 sympy-lamdified 和矢量化函数

python - 在 SymPy 中自动填充矩阵元素