首页 > 解决方案 > python smypy/matplotlib 输入输出与符号方程

问题描述

该程序旨在绘制形状(在解决 I/O 问题之后)。

我使用了我之前编写的程序中的模板来制作这个,但我似乎在这里遗漏了一些东西。我已经尝试过该程序和故障排除,但无法弄清楚。打印语句纯粹是我在故障排除方面所做的努力。

预期的功能是为函数提供一个 numpy 数组,它也会以数组的形式返回适当的 X 和 Y 值。

import sympy as sy
import numpy as np

def rose_func(thetarange):
     _theta = thetarange
     r, x, y, theta = sy.symbols('r, x, y, theta')

     rose_eq = ((((x ** 2 + y ** 2) ** sy.Rational(7 / 2)) + 6 * (
        3 * (x ** 5 * y + x * y ** 5) - 10 * x ** 3 * y ** 3)) / (x ** 2 + y ** 2) ** 3) - 1

     sub_rose = rose_eq.subs([(x, r * sy.cos(thetarange)),
                         (y, r * sy.sin(thetarange))])

     print("subbed eq:", sub_rose)
     print("subbed eq:", sy.latex(sub_rose))
     print()

     simp_rose = sy.simplify(sub_rose)
     print("simplified eq:", simp_rose)
     print("simplified eq:", sy.latex(simp_rose))
     print()

     solv_rose = sy.solve(simp_rose, r)
     print("Solved eq:", solv_rose)
     print("Solved eq:", sy.latex(solv_rose))
     print()

     X = sy.lambdify('r', solv_rose*(int(sy.cos(_theta))), "numpy")  #may need to multiply by r(theta) or theta again

     Y = sy.lambdify('r', solv_rose*(int(sy.sin(_theta))), "numpy")  #may need to multiply by r(theta) or theta again

     return X(_theta), Y(_theta)

 thetavar = np.linspace(-3.14 * 2, 3.14 * 2, 250)

 rose_func(thetavar)

我基于以下程序的工作“模板”:

    def mac_ser(x, N):
    _x = x
    n, z, x = sy.symbols('n, z, x')
    my_equation = sy.summation((z ** n / sy.factorial(n)), (n, 0, N))
    sub_eq = my_equation.subs([(z, -x ** 2)])
    mac_lam = (sy.lambdify('x', sub_eq, "numpy"))
    print("Mac test", mac_lam)
    print("Type is:", type(mac_lam(_x)))
    return (mac_lam(_x))

    x = np.linspace(-2, 2, 1000)
    test = mac_ser(x, 2)

这是我当前的错误:

  File "C:\Users\...\venv\lib\site-packages\sympy\core\cache.py", line 94, in wrapper
    retval = cfunc(*args, **kwargs)
TypeError: unhashable type: 'numpy.ndarray'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\...\venv\lib\site-packages\sympy\core\cache.py", line 94, in wrapper
    retval = cfunc(*args, **kwargs)
TypeError: unhashable type: 'numpy.ndarray'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/.../Roaming/JetBrains/PyCharmCE2020.2/scratches/scratch_21.py", line 51, in <module>
    rose_func(thetavar)
  File "C:/Users/.../Roaming/JetBrains/PyCharmCE2020.2/scratches/scratch_21.py", line 15, in rose_func
    sub_rose = rose_eq.subs([(x, r * sy.cos(thetarange)),
  File "C:\Users\...\venv\lib\site-packages\sympy\core\cache.py", line 96, in wrapper
    retval = func(*args, **kwargs)
  File "C:\Users\...\venv\lib\site-packages\sympy\core\function.py", line 465, in __new__
    result = super().__new__(cls, *args, **options)
  File "C:\Users\...\venv\lib\site-packages\sympy\core\cache.py", line 96, in wrapper
    retval = func(*args, **kwargs)
  File "C:\Users\...\venv\lib\site-packages\sympy\core\function.py", line 280, in __new__
    evaluated = cls.eval(*args)
  File "C:\Users\...\venv\lib\site-packages\sympy\functions\elementary\trigonometric.py", line 570, in eval
    if arg.could_extract_minus_sign():
AttributeError: 'ImmutableDenseNDimArray' object has no attribute 'could_extract_minus_sign'```

标签: pythonnumpysympy

解决方案


人们很难同时使用 numpy 和 sympy 似乎很常见。请记住,numpy 不知道 sympy 存在,并且 sympy 不喜欢基于 numpy 的输入。除非您是两者的专家,否则请不要尝试互换使用它们。请每隔三个问题查看关于堆栈溢出的标签sympy,以查看类似问题并获得理解。

我发现您的代码存在 3 个主要问题:

  1. sympy 函数 lieksy.sin不接受 numpy 数组。您必须为它提供纯 Python 对象(如 ints)或 sympy 对象。
  2. sy.solve在您的情况下返回 2 个解决方案。您需要通过执行类似sy.solve(...)[0]获得第一个解决方案的操作来选择其中一个。
  3. sy.lambdify我认为将字符串作为第一个参数并不合适。使用您在开始时创建的符号。它也是 的theta而不是 的函数r

这是更正,我已经清楚地将 sympy 部分和 numpy 部分分开。

import numpy as np

def generate_rose_func():
    """
    Generates the lambdifed expressions.
    No numpy allowed in this function.
    No sympy allowed out of this function.
    """
    import sympy as sy
    r, x, y, theta = sy.symbols('r, x, y, theta')

    rose_eq = ((((x ** 2 + y ** 2) ** sy.Rational(7 / 2)) + 6 * (
        3 * (x ** 5 * y + x * y ** 5) - 10 * x ** 3 * y ** 3)) / (x ** 2 + y ** 2) ** 3) - 1

    sub_rose = rose_eq.subs([(x, r * sy.cos(theta)),
                             (y, r * sy.sin(theta))])

    print("subbed eq:", sub_rose)
    print("subbed eq:", sy.latex(sub_rose))
    print()

    simp_rose = sy.simplify(sub_rose)
    print("simplified eq:", simp_rose)
    print("simplified eq:", sy.latex(simp_rose))
    print()

    solv_rose = sy.solve(simp_rose, r)[0]  # solve returns 2 solutions in this case. Pick the first one
    print("Solved eq:", solv_rose)
    print("Solved eq:", sy.latex(solv_rose))
    print()

    X = sy.lambdify(theta, solv_rose * sy.cos(theta), "numpy")  # may need to multiply by r(theta) or theta again
    Y = sy.lambdify(theta, solv_rose * sy.sin(theta), "numpy")  # may need to multiply by r(theta) or theta again
    return X, Y

def rose_func(thetarange):
    X, Y = generate_rose_func()
    return X(thetarange), Y(thetarange)

thetavar = np.linspace(-3.14 * 2, 3.14 * 2, 250)
print(rose_func(thetavar))


推荐阅读