【问题标题】:How to use sin(x) and cos(x) functions with eval如何在 eval 中使用 sin(x) 和 cos(x) 函数
【发布时间】:2020-02-16 20:51:46
【问题描述】:

我需要一个程序,它可以使用我在控制台中编写的函数通过 matplotlib 制作图表。 但它不适用于三角函数。 我已经写的代码是:

from numpy import linspace
import matplotlib.pyplot as plt
from math import sin, cos, tan

print("input a:")
a = float(input())
print("input b:")
b = float(input())
x = linspace(a, b, 1001)
y = eval(input())

plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.show()

【问题讨论】:

  • numpy而不是math导入你的函数,即from numpy import linspace, sin, cos, tan,这样它们就可以接受向量输入。
  • 不要只说“它不起作用”!显示错误。其他人猜测您在使用带有numpy 数组xmath.sin 时遇到问题。在这种情况下,错误消息将说明有关创建 Python 标量的内容。

标签: python numpy matplotlib eval trigonometry


【解决方案1】:

我需要制作一个程序来描述我在控制台中编写的功能 我的程序已经适用于例如 x**2 或 x+2,但它不适用于三角函数。我需要我的程序才能做到这两点

【讨论】:

    【解决方案2】:

    我不完全了解您想要做什么,但这可能会有所帮助:

    from numpy import linspace, sin, cos, tan
    import matplotlib.pyplot as plt
    
    a = float(input('Enter x0: '))
    b = float(input('Enter x1: '))
    x = linspace(a, b, 1001)
    
    for trig_func in [sin, cos]:
        y = trig_func(x)
        plt.title(f'{trig_func.__name__}(x)')
        plt.plot(x, y)
        plt.xlabel('x')
        plt.ylabel('y')
        plt.show()
    

    请解释一下您是如何尝试实现 eval 函数的。

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      相关资源
      最近更新 更多