简体   繁体   English

简单微分方程的问题求解和绘图解

[英]Trouble Solving and Plotting Solution to Simple Differential Equation

I'm trying to solve the differential equation R^{2} = 1/R with initial condition that R(0) = 0 in python.我正在尝试用 python 中的 R(0) = 0 的初始条件求解微分方程 R^{2} = 1/R。 I should get the solution that R'(t) = (3/2 * t)^(2/3) as I get this from mathematica.当我从mathematica得到这个时,我应该得到 R'(t) = (3/2 * t)^(2/3) 的解决方案。 Plot of solution to R'[t]^2 = 1/R with initial condition R(0) = 0 Plot 解 R'[t]^2 = 1/R 初始条件 R(0) = 0

I used the following code in python:我在 python 中使用了以下代码:

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

sqrt = np.sqrt

# function that returns dy/dt
def model(y,t):
    #k = 1
    dydt = sqrt(1/y)
    return dydt

# initial condition
y0 = [0.0]

# time points
t = np.linspace(0,5)

# solve ODE
y = odeint(model,y0,t)

# plot results
plt.plot(t,y)
plt.ylabel('$R/R_0$')
plt.xticks([])
plt.yticks([])
plt.show()

however I get only 0 as I'm apparently dividing by zero at some point python plot of differential equation R'[t]^2 = 1/R, which is not correct .但是我只得到 0,因为我显然在某个点除以零python plot 的微分方程 R'[t]^2 = 1/R,这是不正确的 Could someone point out what I could do to get the solution and plot I am expecting.有人可以指出我可以做些什么来获得解决方案和我期待的 plot。

Thank you谢谢

Your model needs to be changed.I get your equation for the solution would be something like thishttps://www.wolframalpha.com/input/?i=R%27%28t%29%5E2+%3D+1%2FR您的 model 需要更改。我知道您的解决方案方程类似于https://www.wolframalpha.com/input/?i=R%27%28t%29%5E2+%3D+1%2FR


import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# function that returns dy/dt
def model(y,t):
    #k = 1
    dydt = 1*y**-1/2
    return dydt
# initial condition
y0 = 0.1

# time points
t = np.linspace(0,20)

# solve ODE
y = odeint(model,y0,t)

# plot results
plt.plot(t,y)
plt.ylabel('$R$')
plt.xlabel('$t$')
plt.xticks([])
plt.yticks([])
plt.show()

Your starting value is 0, which results in the derivative being zero ( y * -1 , or simpler -y ), which means 0 will get added to your current y-value, thus remaining at zero for the whole integration.您的起始值为 0,这导致导数为零( y * -1或更简单的-y ),这意味着 0 将添加到您当前的 y 值,因此在整个积分中保持为零。 Your code is correct, but not your formulation.您的代码是正确的,但不是您的公式。

I see a 1/R in your link, so use that, eg dydt = 1/y ;我在您的链接中看到 1/R,所以使用它,例如dydt = 1/y which will fail, because it results in division by zero, so don't start at zero , because your derivative is not defined there.这将失败,因为它导致除以零,所以不要从零开始,因为你的导数没有在那里定义。 There also appears to be a square root somewhere, that you imported, but never use.某处似乎还有一个平方根,您已导入但从未使用过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM