-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy path8.py
66 lines (47 loc) · 1.25 KB
/
8.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# The Computer Language Benchmarks Game
# https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
#
# Contributed by Sebastien Loisel
# Fixed by Isaac Gouy
# Sped up by Josh Goldfoot
# Dirtily sped up by Simon Descarpentries
# Used list comprehension by Vadim Zelenin
# Concurrency by Jason Stitt
# Concurrency simplified by Matt Vollrath
# Optimized math by Adam Beckmeyer
from itertools import repeat
from math import sqrt
from multiprocessing import Pool
from sys import argv
def eval_A(i, j):
ij = i + j
return ij * (ij + 1) // 2 + i + 1
def A_sum(u, i):
return sum(u_j / eval_A(i, j) for j, u_j in enumerate(u))
def At_sum(u, i):
return sum(u_j / eval_A(j, i) for j, u_j in enumerate(u))
def multiply_AtAv(u):
r = range(len(u))
tmp = pool.starmap(
A_sum,
zip(repeat(u), r)
)
return pool.starmap(
At_sum,
zip(repeat(tmp), r)
)
def main():
n = int(argv[1])
u = [1] * n
for _ in range(10):
v = multiply_AtAv(u)
u = multiply_AtAv(v)
vBv = vv = 0
for ue, ve in zip(u, v):
vBv += ue * ve
vv += ve * ve
result = sqrt(vBv/vv)
print("{0:.9f}".format(result))
if __name__ == '__main__':
with Pool(processes=4) as pool:
main()