python sine and cosine precision

这一生的挚爱 提交于 2019-12-12 17:21:53

问题


How to improve python sine and cosine precision? For example I want to use follow code (just calculate y = cos(acos(x)) for a random complex vector x):

import numpy as np
N = 100000
x = np.zeros(N)+1j*np.zeros(N)
for k in range(0,N):
    x[k] = np.random.normal(0,500)+1j*np.random.normal(0,500)    
y = np.cos(np.arccos(x))

m= np.max(np.abs(x))

print np.max(np.abs(x-y)/m)

y must be equal x. But my difference is approx 1E-9. I think is too big. For example matlab returns less than 1E-15 for the same test. There is some way to improve python precision? Thanks!


回答1:


Before reading this: this may not be a correct answer, because it is extremely unefficient, but if you need extra precission, this could be the best solution.

You can use a Decimal class, where you can calculate with any precition you want (it calculates using string objects, not integers).

>>> from decimal import *
>>> getcontext().prec = 30
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857')

But the problem is that you will have to implement your own trinogometry functions. Luckily python website has provided examples:

https://docs.python.org/3/library/decimal.html#recipes

def cos(x):
    """Return the cosine of x as measured in radians.

    The Taylor series approximation works best for a small value of x.
    For larger values, first compute x = x % (2 * pi).

    >>> print(cos(Decimal('0.5')))
    0.8775825618903727161162815826
    >>> print(cos(0.5))
    0.87758256189
    >>> print(cos(0.5+0j))
    (0.87758256189+0j)

    """
    getcontext().prec += 2
    i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
    while s != lasts:
        lasts = s
        i += 2
        fact *= i * (i-1)
        num *= x * x
        sign *= -1
        s += num / fact * sign
    getcontext().prec -= 2
    return +s

Note that this will affect execution time of your program, because calculating with strings is obviously much slower than with floats.




回答2:


Problem is disappear after python reinstall. Thanks for comments



来源:https://stackoverflow.com/questions/43848038/python-sine-and-cosine-precision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!