如何评估 SymPy 在初始条件下给出的常数?

How to evaluate the constants SymPy gives with initial condition?(如何评估 SymPy 在初始条件下给出的常数?)
本文介绍了如何评估 SymPy 在初始条件下给出的常数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 SymPy 给我的微分方程的解中计算常数 C1 和 C2?有初始条件 f(0)=0 和 f(pi/2)=3.

How can I evaluate the constants C1 and C2 from a solution of a differential equation SymPy gives me? There are the initial condition f(0)=0 and f(pi/2)=3.

>>> from sympy import *
>>> f = Function('f')
>>> x = Symbol('x')
>>> dsolve(f(x).diff(x,2)+f(x),f(x))
f(x) == C1*sin(x) + C2*cos(x)

我尝试了一些 ics 的东西,但它不起作用.示例:

I tried some ics stuff but it's not working. Example:

>>> dsolve(f(x).diff(x,2)+f(x),f(x), ics={f(0):0, f(pi/2):3})
f(x) == C1*sin(x) + C2*cos(x)

顺便说一句:C2 = 0 和 C1 = 3.

By the way: C2 = 0 and C1 = 3.

推荐答案

有一个拉取请求 实现初始/边界条件,已合并并应在 SymPy 1.2 中发布.同时,可以解出这样的常量:

There's a pull request implementing initial/boundary conditions, which was merged and should be released in SymPy 1.2. Meanwhile, one can solve for constants like this:

sol = dsolve(f(x).diff(x,2)+f(x),f(x)).rhs
constants = solve([sol.subs(x,0), sol.subs(x, math.pi/2) - 3])
final_answer = sol.subs(constants)

代码返回 final_answer 作为 3.0*sin(x).

solve 可能会返回一个解决方案列表,在这种情况下,必须替换 constants[0] 等.在任何情况下都强制它返回一个列表(为了一致性),使用 dict=True:

solve may return a list of solutions, in which case one would have to substitute constants[0], etc. To force it to return a list in any case (for consistency), use dict=True:

constants = solve([sol.subs(x,0), sol.subs(x, math.pi/2) - 3], dict=True)
final_answer = sol.subs(constants[0])

如果方程包含参数,solve 可能会也可能不会求解您想要的变量(C1 和 C2).这可以确保如下:

If the equation contains parameters, solve may or may not solve for the variables you want (C1 and C2). This can be ensured as follows:

constants = solve([sol.subs(x,0), sol.subs(x, math.pi/2) - 3], symbols('C1 C2'))

再次,dict=True 将强制输出的列表格式.

where again, dict=True would force the list format of the output.

这篇关于如何评估 SymPy 在初始条件下给出的常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)