数值积分方法问题python [英] numerical integration methods question python

查看:44
本文介绍了数值积分方法问题python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试整合以下公式:

I am trying to integrate the following formula:

下面是我尝试使用 f(a) = sin(a) 的自制方案来执行此集成.

Below is my attempt to perform this integration using a homemade scheme for f(a) = sin(a).

def func(x):
    return math.sin(x)

def integration (f, n, r, a, dtheta ):

    summation = 0
    theta = 0
    while theta <= 2*np.pi:

        f_arg = a + r*np.exp(1j*theta)
        second = np.exp(-1j*theta*n)

        summation += f(f_arg) * second * dtheta
        theta += dtheta

    return math.factorial(n)*summation / (2*np.pi*r**n)

integration(func, n=1, r=1, a=0, dtheta=2*np.pi/10000)

f(a) = sin(a) 的一阶导数 (n=1) 是 f'(a) = cos(a).当在 a = 0 处求值时,这应该给出 cos(0) = 1,但是,它没有.我哪里出错了?

The first derivative (n=1) of f(a) = sin(a) is f'(a) = cos(a). When evaluated at a = 0, this should give cos(0) = 1, however, it does not. Where am I going wrong?

推荐答案

看来你的问题是 math.sin 函数,它不支持复杂参数:

It seems that your problem is the math.sin function, which doesn't support complex arguments:

i = np.exp(.5j * np.pi)
math.sin(i), np.sin(i)
(6.123233995736766e-17, (9.44864380126377e-17+1.1752011936438014j))

它还抛出警告(但不是错误...):

It also throws a warning (but not an error...):

ComplexWarning: Casting complex values to real discards the imaginary part

使用 np.sin 来解决问题.

总的来说,实现可能更容易表达(也更容易调试),更多地使用 numpy,比如

In general, the implementation might be simpler to express (and easier to debug) with more use of numpy, like

def integration(func, a, n, r, n_steps):
    z = r * np.exp(2j * np.pi * np.arange(0, 1, 1. / n_steps))
    return math.factorial(n) * np.mean(func(a + z) / z**n)

np.allclose(1., integration(np.sin, a=0., n=1, r=1., n_steps=100))

True

这篇关于数值积分方法问题python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆