2017-07-18 94 views
3

問題很明顯。我見過幾個pi的例子,但不是用於三角函數。也許可以使用泰勒級數as done here,但我不完全確定如何在Python中實現它。特別是如何存儲這麼多數字。 我應該提到:這個理想情況下會運行在香草python上,也就是沒有numpy等。Python:以高達100萬位的精度計算正弦/餘弦

謝謝!

編輯:爲說,我知道這個問題已經被問過,但它是在Java中,我一直在尋找一個Python實現:)

編輯2:哇,我不知道這裏的人可以如此自已吸收。我確實嘗試了幾種方法,但沒有一種可行。我認爲這是一個你可以尋求建議的地方,你猜我錯了

最後編輯:對於任何人可能會覺得這有用:許多角度可以計算爲sqrt(2),sqrt(3)和Phi (1.61803 ...)因爲這些數字被廣泛使用具有精確到10mio數字,它是有用的,讓他們在一個文件中,並在你的程序讀取它們直接

+1

你應該檢查'decimal'模塊。 –

+0

[精確計算正弦和餘弦函數]可能的副本(https://stackoverflow.com/questions/19797951/calculate-sine-and-cosine-functions-with-precision) –

+5

您是否可以展示*任何*努力實施你鏈接到的算法? –

回答

2

mpmath是這樣的:

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

如果無法安裝mpmath或任何其他模塊的建議你可以嘗試多項式逼近。

enter image description here

其中Rn中Lagrange餘

enter image description here

注意Rn中X移動遠離中心X 0儘快長得快 ,嘗試計算的sin(x)時要小心使用麥克勞林級數(泰勒級數在0居中)COS(x)的任意X

Bad idea: infinity does not exist in computers

Bad idea: infinity does not exist in computers

-1
import math 
x = .5 
def sin(x): 
    sum = 0 
    for a in range(0,50): #this number (50) to be changed for more accurate results 
     sum+=(math.pow(-1,a))/(math.factorial(2*a+1))*(math.pow(x,2*a+1)) 
    return sum 

ans = sin(x) 
print(str.format('{0:.15f}', ans)) #change the 15 for more decimal places 

這裏是實現泰勒級數的例子如上所示使用python。在此之後轉換爲cos並不會太難。

編輯:

添加在最後一行的格式,以實際打印出更多的小數位。

+0

OverflowError:long int太大而無法在範圍爲0到500的範圍內嘗試代碼時轉換爲float :( –

0

試試這個

import math 
from decimal import * 


def sin_taylor(x, decimals): 
    p = 0 
    getcontext().prec = decimals 
    for n in range(decimals): 
     p += Decimal(((-1)**n)*(x**(2*n+1)))/(Decimal(math.factorial(2*n+1))) 
    return p 


def cos_taylor(x, decimals): 
    p = 0 
    getcontext().prec = decimals 
    for n in range(decimals): 
     p += Decimal(((-1)**n)*(x**(2*n)))/(Decimal(math.factorial(2*n))) 
    return p 

if __name__ == "__main__": 
    ang = 0.1 
    decimals = 1000000 
    print 'sin:', sin_taylor(ang, decimals) 
    print 'cos:', cos_taylor(ang, decimals)