简体   繁体   English

Euler在python中的方法

[英]Euler's method in python

I'm trying to implement euler's method to approximate the value of e in python. 我正在尝试实现euler的方法来近似python中e的值。 This is what I have so far: 这是我到目前为止:

def Euler(f, t0, y0, h, N):
    t = t0 + arange(N+1)*h
    y = zeros(N+1)
    y[0] = y0
    for n in range(N):
        y[n+1] = y[n] + h*f(t[n], y[n])
        f = (1+(1/N))^N
    return y

However, when I try to call the function, I get the error "ValueError: shape <= 0". 但是,当我尝试调用该函数时,我收到错误“ValueError:shape <= 0”。 I suspect this has something to do with how I defined f? 我怀疑这与我如何定义f有关? I tried inputting f directly when euler is called, but gave me errors related to variables not being defined. 我在调用euler时尝试直接输入f,但是给了我与未定义的变量相关的错误。 I also tried defining f as its own function, which gave me a division by 0 error. 我也尝试将f定义为它自己的函数,这给了我一个除0错误。

def f(N):
    for n in range(N): 
        return (1+(1/n))^n

(not sure if N was the appropriate variable to use here...) (不确定N是否适合在此使用...)

Are you sure you are not trying to implement the Newton's method? 你确定你没有尝试实施牛顿方法吗? Because Newton's method is used to approximate the roots. 因为牛顿的方法用于近似根。

In case you decide to go with Newton's method, here is a slightly changed version of your code that approximates the square-root of 2. You can change f(x) and fp(x) with the function and its derivative you use in your approximation to the thing you want. 如果你决定使用牛顿方法,这里是一个稍微改变的代码版本,它近似于2的平方根。你可以用你在函数中使用的函数及其派生词改变f(x)fp(x)接近你想要的东西。

import numpy as np

def f(x):
    return x**2 - 2


def fp(x):
    return 2*x

def Newton(f, y0, N):
    y = np.zeros(N+1)
    y[0] = y0
    for n in range(N):
        y[n+1] = y[n] - f(y[n])/fp(y[n])
    return y

print Newton(f, 1, 10)

gives

[ 1. 1.5 1.41666667 1.41421569 1.41421356 1.41421356 1.41421356 1.41421356 1.41421356 1.41421356 1.41421356]

which are the initial value and the first ten iterations to the square-root of two. 这是两个平方根的初始值和前十次迭代。

Besides this a big problem was the usage of ^ instead of ** for powers which is a legal but a totally different (bitwise) operation in python. 除此之外,一个很大的问题是使用^代替**代表权限,这是一个合法但在python中完全不同(按位)的操作。

The formula you are trying to use is not Euler's method, but rather the exact value of e as n approaches infinity wiki , 你试图使用的公式不是Euler的方法,而是e的逼近无限维基的e的精确值,

$n = \lim_{n\to\infty} (1 + \frac{1}{n})^n$

Euler's method is used to solve first order differential equations. 欧拉方法用于求解一阶微分方程。

Here are two guides that show how to implement Euler's method to solve a simple test function: beginner's guide and numerical ODE guide . 这里有两个指南,展示了如何实现Euler方法来解决一个简单的测试函数: 初学者指南数字ODE指南

To answer the title of this post, rather than the question you are asking, I've used Euler's method to solve usual exponential decay: 要回答这篇文章的标题,而不是你要问的问题,我用Euler的方法来解决通常的指数衰减:

$\frac{dN}{dt} = -\lambda N$

Which has the solution, 哪个有解决方案,

$N(t) = N_0 e^{-\lambda t}$

Code: 码:

import numpy as np
import matplotlib.pyplot as plt
from __future__ import division

# Concentration over time
N = lambda t: N0 * np.exp(-k * t)
# dN/dt
def dx_dt(x):
    return -k * x

k = .5
h = 0.001
N0 = 100.

t = np.arange(0, 10, h)
y = np.zeros(len(t))

y[0] = N0
for i in range(1, len(t)):
    # Euler's method
    y[i] = y[i-1] + dx_dt(y[i-1]) * h

max_error = abs(y-N(t)).max()
print 'Max difference between the exact solution and Euler's approximation with step size h=0.001:'

print '{0:.15}'.format(max_error)

Output: 输出:

Max difference between the exact solution and Euler's approximation with step size h=0.001:
0.00919890254720457

Note: I'm not sure how to get LaTeX displaying properly. 注意:我不确定如何正确显示LaTeX。

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

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