简体   繁体   English

由于我正在使用 function,因此如何将浮点数转换为字符串

[英]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 输入的字符串。它通过使用sympyxy代入公式来实现。

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.010.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.

相关问题 我该如何解决这个错误? 我正在和 django 一起做一个学校项目,但我被困住了 - How can i solve this error? I'm working with django on a school project and i'm stuck 我该如何解决这个错误“ufunc&#39;减法&#39;不能使用dtype类型的操作数(&#39; - how can I solve this Error "ufunc 'subtract' cannot use operands with types dtype('<M8[ns]') and dtype('float64')"? 如何解决代码中的 KeyError,我是初学者 - How can I solve a KeyError in my code, I'm a begginer 我如何解决错误''float' object is not iterable' - how can i solve error ''float' object is not iterable' 应该返回浮点数,但它返回“-”我该如何解决这个问题? - Should return float number but it returns “ - ” how can i solve this? 当我尝试在 keras 模型中嵌入序列数据时,如何解决“无法将字符串转换为浮点数:”错误 - How can I solve the 'could not convert string to float:' error when I try to embed sequence data in a keras model 如何将列表字符串转换为浮点数 - How can I convert the list string to a float 如何在 python 中将浮点数格式化为字符串? - How can I format a float as a string in python? 如何确定字符串中是否有浮点数 - How can I identify if a float within a string 隐藏和显示功能,我该如何解决? - Hide and Show function, how can i solve it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM