Last active
December 30, 2023 12:12
-
-
Save terasakisatoshi/0565ec8e6031cabdd2512989f0a8ae49 to your computer and use it in GitHub Desktop.
1.4 倍遅いは嘘な件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Linear congruential generators (LCGs) | |
# Parameters are provided by Park and Miller | |
# See https://c-faq.com/lib/rand.html | |
function LCGs(seed::Integer) | |
a = 48271 | |
m = 2147483647 | |
q, r = divrem(m, a) | |
hi, lo = divrem(seed, q) | |
test = a * lo - r * hi | |
seed = ifelse(test > 0, test, test + m) | |
return seed, Float64(seed) / m | |
end | |
function main() | |
seed = 20231226 | |
num_points = 1000000000 | |
num_inside = 0 | |
for i in eachindex(Base.OneTo(num_points)) | |
seed, x = LCGs(seed) | |
seed, y = LCGs(seed) | |
r2 = x^2 + y^2 | |
num_inside += (r2 < 1.0) | |
end | |
println("pi=", 4.0 * num_inside / num_points) | |
end | |
if abspath(PROGRAM_FILE) == @__FILE__ | |
@time main() | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from numba import jit | |
import time | |
# Linear congruential generators (LCGs) | |
# Parameters are provided by Park and Miller | |
# See https://c-faq.com/lib/rand.html | |
@jit(nopython=True) | |
def LCGs(seed): | |
a = 48271 | |
m = 2147483647 | |
q, r = divmod(m, a) | |
hi, lo = divmod(seed, q) | |
test = a * lo - r * hi | |
if test > 0: | |
seed = test | |
else: | |
seed = test + m | |
rand_num = seed / m | |
return seed, rand_num | |
@jit(nopython=True) | |
def main(): | |
seed = 20231226 | |
num_points = 1000000000 | |
num_inside = 0 | |
for i in range(num_points): | |
seed, x = LCGs(seed) | |
seed, y = LCGs(seed) | |
r2 = x**2 + y**2 | |
num_inside += r2 < 1.0 | |
print("pi =", 4.0 * float(num_inside) / num_points) | |
if __name__ == "__main__": | |
for _ in range(3): | |
s = time.perf_counter() | |
main() | |
e = time.perf_counter() | |
print(f"elapsed {e - s}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考にした記事
https://kamemori.com/research/fortran/speed_montecarlo_lcgs_ja.html
確かに Fortran は速いのですが
Python
Numba ぐらいは試しましょう.
Julia
せめて
divrem
ぐらいの存在は常識にしましょう.https://docs.julialang.org/en/v1/base/math/#Base.divrem
書き方を統一したいという固執によって柔軟さに欠ける特定のプログラミング言語の実行速度を目立たせるような印象操作はかなり悪意を感じます.
また,使用している Julia が 1.7.3 らしいのですが,コミュニテイではすでにメンテナンスされていないバージョンのものです.
https://julialang.org/blog/2019/08/release-process/ の存在すら知らない素人でしょう.Julia のダウンロードページ https://julialang.org/downloads/ からリンクが付けられているので気づいて欲しいです.