今回はhmathで使用されているsinθの計算方法をご紹介します。
計算式
hmathは次の数式でsinθを定義しています。
\sin θ = {\frac{e^{θi}-e^{-θi}}{2i}}
プログラム
hmath内では次のプログラムで計算しています。
sin.py
import hmath
def sin(θ):
return (hmath.exp(θ * 1j) - hmath.exp(θ * -1j)) / 2j
別の計算方法
hmath内では利用していませんが次の式でsinθを計算することもできます。
\sin θ=\sum_{n=0}^{∞}{\frac{(-1)^n}{(2n+1)!}}θ^{2n+1}
上の式をコードにすると次のようになります。
sin.py
import hmath
roop_time = 200 #これを大きくすると精度が上がるがオーバーフローに注意。
def sin(θ):
ans = 0
for n in range(roop_time):
ans += (-1) ** n / hmath.factorial(2 * n + 1) * θ ** (2 * n + 1)
return ans
最後まで見ていだきありがとうございました。
ぜひ活用してみてください。