python - 在 python 中绘制指数的导数 - 知道我做错了什么吗?
问题描述
这是代码:导入东西
import numpy as np
import sympy as sp
from sympy import symbols, diff
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
定义函数及其导数
t = symbols('t')
B = sp.exp(t)
f = sp.diff(B, t)
print(f)
绘图设置
fig1 = plt.figure(1)
ax1 = fig1.gca(projection='3d')
x, t, z = np.meshgrid(np.linspace(-4, 4, 15),
np.linspace(0, 4, 10),
np.linspace(-4, 4, 15))
u = 0
v = 0
ax1.quiver(x, t, z, u, v, f, length = 0.07)
plt.show()
我不断收到“无法转换为浮点数”错误,但程序确实会打印导数,并且在没有导数的情况下使用时也会绘图......
解决方案
这是回溯:
In [8]: ax1.quiver(x, t, z, u, v, f, length = 0.07)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-66e3c3d2c6bf> in <module>
----> 1 ax1.quiver(x, t, z, u, v, f, length = 0.07)
/usr/local/lib/python3.6/dist-packages/mpl_toolkits/mplot3d/axes3d.py in quiver(self, length, arrow_length_ratio, pivot, normalize, *args, **kwargs)
2620
2621 XYZ = np.column_stack(input_args[:3])
-> 2622 UVW = np.column_stack(input_args[3:argi]).astype(float)
2623
2624 # Normalize rows of UVW
/usr/local/lib/python3.6/dist-packages/sympy/core/expr.py in __float__(self)
278 if result.is_number and result.as_real_imag()[1]:
279 raise TypeError("can't convert complex to float")
--> 280 raise TypeError("can't convert expression to float")
281
282 def __complex__(self):
TypeError: can't convert expression to float
显然它试图将u,v,f
参数转换为数字数组。
In [9]: np.column_stack([u,v,f])
Out[9]: array([[0, 0, exp(t)]], dtype=object)
float(exp(t))
不起作用。 f
是一个同情的表达;你不能把它变成一个数字。
潜在的问题是您正在尝试使用数字绘图函数来绘制符号表达式。 sympy
并且numpy
不能无缝地协同工作。要么使用sympy's
绘图工具,要么将您的表达式转换为数字表达式 - 在某些点计算的数字数组。
===
ax1.quiver(x, t, z, u, v, np.exp(t), length = 0.07)
运行。 np.exp(t)
是一个数组,大小与 相同t
。
===
Sympy 绘图:
In [12]: from sympy.plotting import plot
In [13]: plot(f)
Out[13]: <sympy.plotting.plot.Plot at 0x7f02b0f99400>
https://docs.sympy.org/latest/modules/plotting.html
===
https://docs.sympy.org/latest/tutorial/basic_operations.html#lambdify
lambdify
是sympy
弥合 sympy 和 numpy 之间差距的工具。它从 sympy 表达式生成一个numpy
(默认)函数:
In [27]: fn=lambdify(symbols('t'),f)
In [28]: fn
Out[28]: <function _lambdifygenerated(t)>
In [29]: fn(t).shape # evaluate a the 3d array `t`
Out[29]: (10, 15, 15)
现在我们有了适用于的数字数组quiver
:
In [36]: ax1.quiver(x, t, z, u, v, fn(t), length = 0.07)
Out[36]: <mpl_toolkits.mplot3d.art3d.Line3DCollection at 0x7f02b0f24e80>
推荐阅读
- excel - Exist function in dictionary doesn't work for an object as Key created in a class module
- c# - 为系统循环创建高性能组件池
- python - 为什么某些网站出现 urllib 错误
- mysql - 如何减少查询的执行时间
- laravel - 如何在 Laravel 中导入具有各种模型(和子数据/模型)的单个 excel 文件/工作表?
- python - Numpy:从熊猫数据帧创建可变长度序列
- java - 从 Jhipster 中的 URL 中删除哈希 (#) (java 和 angular 6)
- css - 使用 scss 执行包含通用部分和特定部分的最小 css 规则集?
- amazon-web-services - docker 输出中的 AWS 会话管理器 ^@ 无限期
- .net - When does Start-Service know that win service actually completed full startup process and is in fully operational state?