python泰勒展开,Python:使用泰勒级数逼近ln(x)

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;

54ed0cacb65c1570301eb072934a6b71.png

(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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值