-
Notifications
You must be signed in to change notification settings - Fork 103
/
lib.ivy
executable file
·44 lines (30 loc) · 1.19 KB
/
lib.ivy
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
# Average
op avg x = (+/x)/rho x
# Largest n in x.
op n largest x = n take x[down x]
# Digits of a base b. Use log to decide how many.
op a base b = ((floor 1 + b log a) rho b) encode a
# Count the number of appearances of each digit in x.
op digitcount x = t = text x; +/(-1+iota 10) o.== (code (t in '0123456789') sel t) - code '0'
# Population count. Use encode (through base) to turn the value into a string of bits.
op popcount n = +/n base 2
# Sum of digits.
op sumdigits x = t = text x; +/(code (t in '0123456789') sel t) - code '0'
# Meters to feet.
op m2ft m = 0 12 encode ceil m*1000/25.4
# Miles to kilometers
op mi2km m = float m*1.609344
# Celsius to Fahrenheit.
op c2f c = float 32 + c * 9/5
# Fahrenheit to Celsius.
op f2c f = float 5/9 * f - 32
# Kilometers to miles
op km2mi m = float m/1.609344
# Some crazy math. Avoid N ≳1000; these nutty routines take too long.
# Primes less <= N
op primes N = (not T in T o.* T) sel T = 1 drop iota N
# Approximations to pi.
op approxPi N = sqrt 6*+/ /(iota N)**2
# A much more efficient version found by PSLQ. See Nature, Vol 590, page 69.
op PSLQpiTerm N = (/16**N)* (4 / 1+8*N)-(2 / 4+8*N)+(/5+8*N)+(/6+8*N)
op PSLQpi N = +/PSLQpiTerm -1 + iota N