Python:使用泰勒级数逼近ln(x) [英] Python: Approximating ln(x) using Taylor Series

查看:504
本文介绍了Python:使用泰勒级数逼近ln(x)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在十位数的精度内建立ln(1.9)的近似值(so .641853861).

我正在使用从ln [(1 + x)/(1-x)]构建的简单函数

到目前为止,这是我的代码:

# function for ln[(1 + x)/(1 - x)]

def taylor_two(r, n):
    x = 0.9 / 2.9
    i = 1
    taySum = 0
    while i <= n:
        taySum += (pow(x,i))/(i)
        i += 2
    return 2 * taySum

print taylor_two(x, 12)

print taylor_two(x, 17)

我现在要做的是重新设置格式,以便告诉我将ln(1.9)近似于上述10位数字所需的项数,让它显示序列给出的值,并显示错误./p>

我认为我需要以某种方式将函数构建到for循环中,但是一旦达到所需的10位数字,如何才能停止迭代呢?

谢谢您的帮助!

解决方案

原理是;

  • 看看每次迭代会增加多少结果.
  • 当差异小于1e-10时停止.

您正在使用以下公式,对;

(请注意有效范围!)

def taylor_two():
    x = 1.9 - 1
    i = 1
    taySum = 0
    while True:
        addition = pow(-1,i+1)*pow(x,i)/i
        if abs(addition) < 1e-10:
            break
        taySum += addition
        # print('value: {}, addition: {}'.format(taySum, addition))
        i += 1
    return taySum

测试:

In [2]: print(taylor_two())
0.6418538862240631

In [3]: print('{:.10f}'.format(taylor_two()))
0.6418538862

I'm trying to build an approximation for ln(1.9) within ten digits of accuracy (so .641853861).

I'm using a simple function I've built from ln[(1 + x)/(1 - x)]

Here is my code so far:

# function for ln[(1 + x)/(1 - x)]

def taylor_two(r, n):
    x = 0.9 / 2.9
    i = 1
    taySum = 0
    while i <= n:
        taySum += (pow(x,i))/(i)
        i += 2
    return 2 * taySum

print taylor_two(x, 12)

print taylor_two(x, 17)

What I need to do now is reformat this so that it tells me the number of terms needed to approximate ln(1.9) to the above 10 digits, have it display the value that series gives, and also show the error.

I assume I need to build my function into a for loop somehow, but how can I get it to stop iterating once it's reached the 10 digits needed?

Thank you for your help!

解决方案

The principle is;

  • Look at how much each iteration adds to the result.
  • Stop when the difference is smaller than 1e-10.

You're using the following formula, right;

(Note the validity range!)

def taylor_two():
    x = 1.9 - 1
    i = 1
    taySum = 0
    while True:
        addition = pow(-1,i+1)*pow(x,i)/i
        if abs(addition) < 1e-10:
            break
        taySum += addition
        # print('value: {}, addition: {}'.format(taySum, addition))
        i += 1
    return taySum

Test:

In [2]: print(taylor_two())
0.6418538862240631

In [3]: print('{:.10f}'.format(taylor_two()))
0.6418538862

这篇关于Python:使用泰勒级数逼近ln(x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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