python-为什么SymPy不简化表达式?

前端之家收集整理的这篇文章主要介绍了python-为什么SymPy不简化表达式? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我只是查看Python模块SymPy,并尝试作为一个简单(无用)的示例,在给定的时间间隔内将函数f(x)与函数set g_i(x)拟合.

import sympy as sym

def functionFit(f,funcset,interval):
    N = len(funcset) - 1
    A = sym.zeros(N+1,N+1)
    b = sym.zeros(N+1,1)
    x = sym.Symbol('x')

    for i in range(N+1):
        for j in range(i,N+1):
            A[i,j] = sym.integrate(funcset[i]*funcset[j],(x,interval[0],interval[1]))
            A[j,i] = A[i,j]

        b[i,0] = sym.integrate(funcset[i]*f,interval[1]))

    c = A.LUsolve(b)
    u = 0

    for i in range(len(funcset)):
        u += c[i,0]*funcset[i]

    return u,c


x = sym.Symbol('x')
f = 10*sym.cos(x)+3*sym.sin(x)
fooset=(sym.sin(x),sym.cos(x))
interval = (1,2)
print("function to approximate:",f)
print("Basic functions:")

for foo in fooset:
    print(" - ",foo)

u,c = functionFit(f,fooset,interval)

print()
print("simplified u:")
print(sym.simplify(u))
print()
print("simplified c:")
print(sym.simplify(c))

结果是要返回的拟合函数u(x)以及functionFit的系数.

就我而言

 f(x) = 10 * sym.cos(x) + 3 * sym.sin(x)

我想根据sin(x),cos(x)的线性组合来拟合它.
因此系数应为3和10.

结果很好,但是对于u(x)我得到

 u(x) = (12*sin(2)**2*sin(4)*sin(x) + 3*sin(8)*sin(x) + 12*sin(2)*sin(x) + 40*sin(2)**2*sin(4)*cos(x) + 10*sin(8)*cos(x) + 40*sin(2)*cos(x))/(2*(sin(4) + 2*sin(2))) : 

Function to approximate: 3*sin(x) + 10*cos(x) 

Basic functions:
      -  sin(x)
      -  cos(x)

Simplified u: (12*sin(2)**2*sin(4)*sin(x) + 3*sin(8)*sin(x) + 12*sin(2)*sin(x) + 40*sin(2)**2*sin(4)*cos(x) + 10*sin(8)*cos(x) + 40*sin(2)*cos(x))/(2*(sin(4) + 2*sin(2)))

Simplified c: Matrix([[3],[10]])

的确与10 * cos(x)3 * sin(x)相同.
但是,我想知道为什么不将其简化为该表达.我尝试了几种可用的简化函数,但没有一个能提供预期的结果.

我的代码有什么问题吗?还是我的期望很高?

最佳答案
不知道这是否是您的解决方案,但我只会在每个Sympy表达式中使用.evalf方法

In [26]: u.simplify()                                                                     
Out[26]: (12*sin(2)**2*sin(4)*sin(x) + 3*sin(8)*sin(x) + 12*sin(2)*sin(x) + 40*sin(2)**2*sin(4)*cos(x) + 10*sin(8)*cos(x) + 40*sin(2)*cos(x))/(2*(sin(4) + 2*sin(2)))

In [27]: u.evalf()                                                                        
Out[27]: 3.0*sin(x) + 10.0*cos(x)

In [28]:                                                                                  
原文链接:https://www.f2er.com/python/533138.html

猜你在找的Python相关文章