Python:以高达 100 万位的精度计算正弦/余弦 [英] Python: Calculate sine/cosine with a precision of up to 1 million digits

查看:44
本文介绍了Python:以高达 100 万位的精度计算正弦/余弦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是不言自明的.我已经看到了几个 pi 的例子,但没有看到 trigo 函数的例子.也许人们可以使用泰勒级数

其中 Rn拉格朗日余数

注意 Rnx 远离中心 x0 时增长很快,所以尝试计算任意的sin(x)cos(x)时,请小心使用麦克劳林级数(以0为中心的泰勒级数) x.

Question is pretty self-explanatory. I've seen a couple of examples for pi but not for trigo functions. Maybe one could use a Taylor series as done here but I'm not entirely sure how to implement that in python. Especially how to store so many digits. I should mention: this ideally would run on vanilla python i.e. no numpy etc.

Thanks!

Edit: as said, I know the question has been asked before but it's in java and I was looking for a python implementation :)

Edit 2: wow I wasn't aware people here can be so self-absorbed. I did try several approaches but none would work. I thought this a place you can ask for advice, guess I was wrong

last edit: For anyone who might find this useful: many angles can be calculated as a multiple of sqrt(2), sqrt(3) and Phi (1.61803..) Since those numbers are widely available with a precision up to 10mio digits, it's useful to have them in a file and read them in your program directly

解决方案

mpmath is the way:

from mpmath import mp
precision = 1000000
mp.dps = precision
mp.cos(0.1)


If unable to install mpmath or any other module you could try polynomial approximation as suggested.

where Rn is the Lagrange Remainder

Note that Rn grows fast as soon as x moves away from the center x0, so be careful using Maclaurin series (Taylor series centered in 0) when trying to calculate sin(x) or cos(x) of arbitrary x.

这篇关于Python:以高达 100 万位的精度计算正弦/余弦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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