11

More than 3 years have passed since last update.

posted at

updated at

# Pythonの平方根どれが早いか

## はじめに

Pythonの平方根でどの方法が早いかを試しました。

みんな兢プロでは、`math.sqrt(n)`を使おうな!
でもタイプ数や速度的に、`n ** 0.5`でもいいと思ってます。

• Python 3.6.8

## 試した方法

• n ** 0.5
• pow(n, 0.5)
• math.sqrt(n)
• numpy.sqrt(n)
• sympy.sqrt(n)
• scipy.sqrt(n)
``````
import math
import numpy as np
import sympy
import scipy

n = 12345678910
``````
``````
%timeit -r 3 -n 1000 n ** 0.5
# 1000 loops, best of 3: 136 ns per loop
%timeit -r 3 -n 1000 pow(n, 0.5)
# 1000 loops, best of 3: 183 ns per loop
%timeit -r 3 -n 1000 math.sqrt(n)
# 1000 loops, best of 3: 70.7 ns per loop
%timeit -r 3 -n 1000 np.sqrt(n)
# 1000 loops, best of 3: 930 ns per loop
%timeit -r 3 -n 1000 sympy.sqrt(n)
# 1000 loops, best of 3: 1.27 µs per loop
%timeit -r 3 -n 1000 int(scipy.sqrt(n))
# 1000 loops, best of 3: 7.7 µs per loop
``````

## テストコード

gist: sqrt.ipynb

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
What you can do with signing up
11