1
1

More than 1 year has passed since last update.

cosθ の 計算方法(Python)

Posted at

今回はhmathで使用されているcosθの計算方法をご紹介します。

計算式

hmathは次の数式でcosθを定義しています。

\cos θ = {\frac{e^{θi}+e^{-θi}}{2}}

プログラム

hmath内では次のプログラムで計算しています。

cos.py
import hmath
def cos(θ):
    return (hmath.exp(θ * 1j) + hmath.exp(θ * -1j)) / 2

別の計算方法

hmath内では利用していませんが次の式でcosθを計算することもできます。

\cos θ=\sum_{n=0}^{∞}{\frac{(-1)^n}{(2n)!}}θ^{2n}

上の式をコードにすると次のようになります。

cos.py
import hmath
roop_time = 200 #これを大きくすると精度が上がるがオーバーフローに注意。
def cos(θ):
    ans = 0
    for n in range(roop_time):
        ans += (-1) ** n / hmath.factorial(2 * n) * θ ** (2 * n)
    return ans

最後まで見ていだきありがとうございました。
ぜひ活用してみてください。

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1