[英]sympy's plot_parametric says TypeError: can't convert complex to float
I want to plot a curve which is actually has a S shape: 我想绘制一条实际上具有S形的曲线:
but the code says TypeError: can't convert complex to float
. 但代码显示TypeError: can't convert complex to float
。 Where is the complex number? 复数在哪里? how to fix it? 如何解决? Thanks 谢谢
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's plot
involves some error-prone manipulations meant to boost the performance of plots; SymPy的plot
涉及一些易于出错的操作,旨在提高绘图的性能。 they involve complex
data type which sometimes leads to errors when inequalities are involved. 它们涉及complex
数据类型,当涉及不平等时,有时会导致错误。 Reducing the number of inequalities helps in this case: 在这种情况下,减少不平等的数量将有所帮助:
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))
The above is how Piecewise is usually presented in SymPy: conditions are evaluated in the order given, and the first one to be True results in the evaluation of the corresponding expression. 上面是在SymPy中通常以逐段方式表示的:条件是按给定的顺序求值的,第一个条件为True的是对相应表达式求值的结果。 ( u <= boundUpper
could be replaced by True
, by the way.) Result: ( u <= boundUpper
可以由True
代替。)结果:
This is still not ideal. 这仍然不是理想的。 The horizontal line from 0 to 4 should not be there, of course - it's an artifact of plotting. 当然,从0到4的水平线不应该在那儿-这是绘图的产物。 Also, this code displays 另外,此代码显示
UserWarning: The evaluation of the expression is problematic. 用户警告:表达式的评估是有问题的。 We are trying a failback method that may still work. 我们正在尝试一种仍然可以使用的故障回复方法。 Please report this as a bug. 请将此报告为错误。
I suggest to avoid Piecewise in plotting. 我建议避免在绘图中使用分段式。 Instead combine a plot from pieces using extend
as shown below. 取而代之的是使用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()
Output (no warnings and no artifacts). 输出(无警告,无伪影)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.