MatLab与Python欧拉方程

时间:2016-01-02 16:33:13

标签: python matlab for-loop plot

所以我正在尝试学习python,我认为这样做的一个好方法是采用我之前在MatLab中完成的问题集并将它们转换为Python。这是我正在使用的 MatLab 代码

% C14 halflife is 5726 years
% The time constant tau is t(1/2)/ln2 = 8260 y

N0=10000; %initialize N0
tau=8260; %Carbon 14 

tmax=40000; %max time value, will be on the x-axis

% Generate data using exact values
t1=linspace(0,tmax,100);
N1=N0*exp(-t1/tau);%Here we introduce the equation for nuclear decay
figure
plot1 = plot(t1,N1);

% Generate data using Euler

Step=1000;
N=N0;
NumRes=N;
tx=0:Step:tmax;
% This is the taylor series generation of data. 
for t=Step:Step:tmax

    N=N-Step*N/tau;
    NumRes=[NumRes,N];

end

% Plot the approximation

 hold on
plot2 = plot(tx,NumRes,'+');

我为python找到了解决方案的确切部分,如下所示。但我无法得到近似部分。

import numpy as np
import matplotlib.pyplot as plt

def exact(NO, decay, tmax):
    t2 = np.linspace(0,tmax,100)
    N2 = NO * np.exp(-t2/decay)
    plt.plot(t2,N2)
exact(10000,8260,40000)

我无法弄清楚如何获得近似部分,但这是我的尝试...

Step = 1000
N = 10000
tau = 8260
tx = xrange(0,40000,Step)
result= []
for i in xrange(Step,40000,Step):
    result = N - Step*N/tau

plt.plot(tx,result)
plt.show()

我收到错误消息

     plt.plot(tx,result)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3154, in plot
    ret = ax.plot(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/__init__.py", line 1811, in inner
    return func(ax, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/axes/_axes.py", line 1427, in plot
    for line in self._get_lines(*args, **kwargs):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 386, in _grab_next_args
    for seg in self._plot_args(remaining, kwargs):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 364, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 223, in _xy_from_xy
    raise ValueError("x and y must have same first dimension")
ValueError: x and y must have same first dimension

我是python的新手,显然我的代码错了。我很乐意为您提供任何帮助。

1 个答案:

答案 0 :(得分:6)

您的代码中存在多个问题:

  • 您取代结果而不是附加值。
  • 您正在进行整数除法/(因为所有操作数都是整数)。
  • 您正在循环xrange(Step, 40000, Step)txxrange(0, 40000, Step),因此txresult的大小永远不会相同。

以下是对代码的更正:

Step   = 1000
N      = 10000.0 # Use a float instead of an int here
tau    = 8260
tx     = xrange(0, 40000, Step)
result = [N] # Start with a list containing only N
for i in xrange(Step, 40000, Step):
    N = N - Step * N / tau # Update N
    result.append(N) # Append N to result
plt.plot(tx, result)
plt.show()

由于您使用的是numpy,因此以下是一种更直接的方法:

tx = numpy.arange(0, 40000, Step)
ty = N * (1 - Step / tau) ** numpy.arange(0, tx.size)