今回は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
最後まで見ていだきありがとうございました。
ぜひ活用してみてください。