[英]How can I solve float to string since I'm working with a function
I'm practicing python and I've encountered an error with string to float error.我正在练习 python,我遇到了 string to float 错误。 My intention is to give a function as an input, where I can put ^ as an indicative of **.我的意图是提供 function 作为输入,我可以将 ^ 作为 ** 的指示。 Then, the 3d graph, related to the function, will be shown.然后,将显示与 function 相关的 3d 图。 I've searched for the string to float error, but since my function need to have special characters, the solutions didn't work for my case.我已经搜索了要浮动的字符串错误,但由于我的 function 需要有特殊字符,因此解决方案不适用于我的情况。
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import random
funciao = []
func = input("Enter your function: ")
function = func.replace('^','**')
def fun(x,y):
return function
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-3.0, 3.0, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)
ax.plot_surface(X, Y, Z)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
This works:这有效:
import sympy
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import random
funciao = []
func = input("Enter your function: ")
function = func.replace('^', '**')
def fun(x, y):
in_dict = {
"x": x,
"y": y
}
subs = {sympy.symbols(key): item for key, item in in_dict.items()}
ans = sympy.simplify(function).evalf(subs=subs)
return str(ans)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-3.0, 3.0, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array([fun(x, y) for x, y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)
ax.plot_surface(X, Y, Z)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
Now fun()
will actually return the correct numerical string values, rather than function
which is just the string you entered for the function. It does this by subbing in x
and y
into the formula using sympy
.现在fun()
实际上会返回正确的数字字符串值,而不是function
,后者只是您为 function 输入的字符串。它通过使用sympy
将x
和y
代入公式来实现。
Note: You will need to install sympy
, and the math for this in high definition will be very slow.注意:您将需要安装sympy
,并且高清的数学运算会非常慢。 So be prepared to wait a while for a graph to appear.因此,请准备好等待一段时间图表出现。
Consider changing this line x = y = np.arange(-3.0, 3.0, 0.01)
to x = y = np.arange(-3.0, 3.0, 0.5)
.考虑将此行x = y = np.arange(-3.0, 3.0, 0.01)
更改为x = y = np.arange(-3.0, 3.0, 0.5)
。 Which will generate the data much quicker (resolution from 0.01
to 0.5
).这将更快地生成数据(分辨率从0.01
到0.5
)。
You can also define zs
in a tqdm
loop to see the progress bar:您还可以在tqdm
循环中定义zs
以查看进度条:
from tqdm import tqdm
# ...
zs = []
for x, y in tqdm(zip(np.ravel(X), np.ravel(Y)), total=len(np.ravel(X)),desc="Calculating data"):
zs.append(fun(x, y))
zs = np.array(zs)
# ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.