chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 12:32:53 +08:00
commit 2a16f2f53b
247 changed files with 69150 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
"""
This script uses the cplot function in mpmath to plot the Mandelbrot set.
By default, the fp context is used for speed. The mp context could be used
to improve accuracy at extremely high zoom levels.
"""
import mpmath
ctx = mpmath.fp
# ctx = mpmath.mp
ITERATIONS = 50
POINTS = 100000
ESCAPE_RADIUS = 8
# Full plot
RE = [-2.5, 1.5]
IM = [-1.5, 1.5]
# A pretty subplot
#RE = [-0.96, -0.80]
#IM = [-0.35, -0.2]
def mandelbrot(z):
c = z
for i in range(ITERATIONS):
zprev = z
z = z*z + c
if abs(z) > ESCAPE_RADIUS:
return ctx.exp(1j*(i + 1 - ctx.log(ctx.log(abs(z)))/ctx.log(2)))
return 0
ctx.cplot(mandelbrot, RE, IM, points=POINTS, verbose=1)
+106
View File
@@ -0,0 +1,106 @@
"""
This script calculates solutions to some of the problems from the
"Many Digits" competition:
http://www.cs.ru.nl/~milad/manydigits/problems.php
Run with:
python manydigits.py
"""
from mpmath import (asin, asinh, atan, atanh, catalan, cos, e, exp, findroot,
mp, mpf, pi, quadts, sin, sqrt, tan, tanh, zeta)
from mpmath.libmp.libintmath import bin_to_radix
from mpmath.libmp.libmpf import to_fixed
dps = 100
mp.dps = dps + 10
def pr(x):
"""Return the first dps digits after the decimal point"""
x = x._mpf_
p = int(dps*3.33 + 10)
t = to_fixed(x, p)
d = bin_to_radix(t, p, 10, dps)
s = str(d).zfill(dps)[-dps:]
return s[:dps//2] + "\n" + s[dps//2:]
print("""
This script prints answers to a selection of the "Many Digits"
competition problems: http://www.cs.ru.nl/~milad/manydigits/problems.php
The output for each problem is the first 100 digits after the
decimal point in the result.
""")
print("C01: sin(tan(cos(1)))")
print(pr(sin(tan(cos(1)))))
print()
print("C02: sqrt(e/pi)")
print(pr(sqrt(e/pi)))
print()
print("C03: sin((e+1)^3)")
print(pr(sin((e+1)**3)))
print()
print("C04: exp(pi*sqrt(2011))")
mp.dps += 65
print(pr(exp(pi*sqrt(2011))))
mp.dps -= 65
print()
print("C05: exp(exp(exp(1/2)))")
print(pr(exp(exp(exp(0.5)))))
print()
print("C06: arctanh(1-arctanh(1-arctanh(1-arctanh(1/pi))))")
print(pr(atanh(1-atanh(1-atanh(1-atanh(1/pi))))))
print()
print("C07: pi^1000")
mp.dps += 505
print(pr(pi**1000))
mp.dps -= 505
print()
print("C08: sin(6^(6^6))")
print(pr(sin(6**(6**6))))
print()
print("C09: sin(10*arctan(tanh(pi*(2011^(1/2))/3)))")
mp.dps += 150
print(pr(sin(10*atan(tanh(pi*sqrt(2011)/3)))))
mp.dps -= 150
print()
print("C10: (7+2^(1/5)-5*(8^(1/5)))^(1/3) + 4^(1/5)-2^(1/5)")
a = mpf(1)/5
print(pr(((7 + 2**a - 5*(8**a))**(mpf(1)/3) + 4**a - 2**a)))
print()
print("C11: tan(2^(1/2))+arctanh(sin(1))")
print(pr((tan(sqrt(2)) + atanh(sin(1)))))
print()
print("C12: arcsin(1/e^2) + arcsinh(e^2)")
print(pr(asin(1/exp(2)) + asinh(exp(2))))
print()
print("C17: S= -4*Zeta(2) - 2*Zeta(3) + 4*Zeta(2)*Zeta(3) + 2*Zeta(5)")
print(pr(-4*zeta(2) - 2*zeta(3) + 4*zeta(2)*zeta(3) + 2*zeta(5)))
print()
print(r"C18: Catalan G = Sum{i=0}{\infty}(-1)^i/(2i+1)^2")
print(pr(catalan))
print()
print("C21: Equation exp(cos(x)) = x")
print(pr(findroot(lambda x: exp(cos(x))-x, 1)))
print()
print("C22: J = integral(sin(sin(sin(x)))), x=0..1")
print(pr(quadts(lambda x: sin(sin(sin(x))), [0, 1])))
print()
+82
View File
@@ -0,0 +1,82 @@
"""
Calculate digits of pi. This module can be run interactively with
python pidigits.py
"""
import math
import sys
from time import perf_counter
from mpmath.libmp.libelefun import pi_fixed
from mpmath.libmp.libintmath import bin_to_radix, numeral
def display_fraction(digits, skip=0, colwidth=10, columns=5):
perline = colwidth * columns
printed = 0
for linecount in range((len(digits)-skip) // (colwidth * columns)):
line = digits[skip+linecount*perline:skip+(linecount+1)*perline]
for i in range(columns):
print(line[i*colwidth : (i+1)*colwidth], end=' ')
print(":", (linecount+1)*perline)
if (linecount+1) % 10 == 0:
print()
printed += colwidth*columns
rem = (len(digits)-skip) % (colwidth * columns)
if rem:
buf = digits[-rem:]
s = ""
for i in range(columns):
s += buf[:colwidth].ljust(colwidth+1, " ")
buf = buf[colwidth:]
print(s + ":", printed + colwidth*columns)
def calculateit(base, n, tofile):
intpart = numeral(3, base)
skip = 1
if base <= 3:
skip = 2
prec = int(n*math.log(base,2))+10
print("Step 1 of 2: calculating binary value...")
t = perf_counter()
a = pi_fixed(prec, verbose=True, verbose_base=base)
step1_time = perf_counter() - t
print("Step 2 of 2: converting to specified base...")
t = perf_counter()
d = bin_to_radix(a, prec, base, n)
d = numeral(d, base, n)
step2_time = perf_counter() - t
print("\nWriting output...\n")
if tofile:
out_ = sys.stdout
sys.stdout = tofile
print("%i base-%i digits of pi:\n" % (n, base))
print(intpart, ".\n")
display_fraction(d, skip, colwidth=10, columns=5)
if tofile:
sys.stdout = out_
print("\nFinished in %f seconds (%f calc, %f convert)" % \
((step1_time + step2_time), step1_time, step2_time))
def interactive():
print("Compute digits of pi with mpmath\n")
base = input("Which base? (2-36, 10 for decimal) \n> ")
digits = input("How many digits? (enter a big number, say, 10000)\n> ")
tofile = input("Output to file? (enter a filename, or just press " \
"enter\nto print directly to the screen) \n> ")
if tofile:
tofile = open(tofile, "w")
calculateit(int(base), int(digits), tofile)
input("\nPress enter to close this script.")
if __name__ == "__main__":
interactive()
+35
View File
@@ -0,0 +1,35 @@
"""
Function plotting demo.
"""
from mpmath import *
def main():
print("""
Simple function plotting. You can enter one or several
formulas, in ordinary Python syntax and using the mpmath
function library. The variable is 'x'. So for example
the input "sin(x/2)" (without quotation marks) defines
a valid function.
""")
functions = []
for i in range(10):
if i == 0:
s = input('Enter a function: ')
else:
s = input('Enter another function (optional): ')
if not s:
print()
break
f = eval("lambda x: " + s)
functions.append(f)
print("Added f(x) = " + s)
print()
xlim = input('Enter xmin, xmax (optional): ')
if xlim:
xlim = eval(xlim)
else:
xlim = [-5, 5]
print("Plotting...")
plot(functions, xlim=xlim)
main()
+63
View File
@@ -0,0 +1,63 @@
'''
This script calculates the constant in Gerver's solution to the moving sofa
problem.
See Finch, S. R. "Moving Sofa Constant." §8.12 in Mathematical Constants.
Cambridge, England: Cambridge University Press, pp. 519-523, 2003.
'''
from mpmath import cos, sin, pi, quad, findroot, mp
mp.prec = 113
eqs = [lambda A, B, φ, θ: (A*(cos(θ) - cos(φ)) - 2*B*sin(φ)
+ (θ - φ - 1)*cos(θ) - sin(θ) + cos(φ) + sin(φ)),
lambda A, B, φ, θ: (A*(3*sin(θ) + sin(φ)) - 2*B*cos(φ)
+ 3*(θ - φ - 1)*sin(θ) + 3*cos(θ) - sin(φ) + cos(φ)),
lambda A, B, φ, θ: A*cos(φ) - (sin(φ) + 0.5 - 0.5*cos(φ) + B*sin(φ)),
lambda A, B, φ, θ: ((A + pi/2 - φ - θ) - (B - (θ - φ)*(1 + A)/2
- 0.25*(θ - φ)**2))]
A, B, φ, θ = findroot(eqs, (0, 0, 0, 0))
def r(α):
if 0 <= α < φ:
return 0.5
if φ <= α < θ:
return (1 + A + α - φ)/2
if θ <= α < pi/2 - θ:
return A + α - φ
return B - (pi/2 - α - φ)*(1 + A)/2 - (pi/2 - α - φ)**2/4
s = lambda α: 1 - r(α)
def u(α):
if φ <= α < θ:
return B - (α - φ)*(1 + A)/2 - (α - φ)**2/4
return A + pi/2 - φ - α
def du(α):
if φ <= α < θ:
return -(1 + A)/2 - (α - φ)/2
return -1
def y(α, f):
if α > pi/2 - θ:
i = [0, φ, θ, pi/2 - θ, α]
elif α > θ:
i = [0, φ, θ, α]
elif α > φ:
i = [0, φ, α]
else:
i = i = [0, α]
return 1 - quad(lambda x: f(x)*sin(x), i)
y1 = lambda α: y(α, r)
y2 = lambda α: y(α, s)
y3 = lambda α: y2(α) - u(α)*sin(α)
S1 = quad(lambda x: y1(x)*r(x)*cos(x), [0, φ, θ, pi/2 - θ, pi/2 - φ])
S2 = quad(lambda x: y2(x)*s(x)*cos(x), [0, φ, θ])
S3 = quad(lambda x: y3(x)*(u(x)*sin(x) - du(x)*cos(x) - s(x)*cos(x)),
[φ, θ, pi/4])
print(2*(S1 + S2 + S3))
+71
View File
@@ -0,0 +1,71 @@
"""
Interval arithmetic demo: estimating error of numerical Taylor series.
This module can be run interactively with
python taylor.py
"""
from mpmath import mpi, exp, factorial, mpf
def taylor(x, n):
print("-"*75)
t = x = mpi(x)
s = 1
print("adding 1")
print(s, "\n")
s += t
print("adding x")
print(s, "\n")
for k in range(2, n+1):
t = (t * x) / k
s += t
print("adding x^%i / %i! ~= %s" % (k, k, t.mid))
print(s, "\n")
print("-"*75)
return s
# Note: this should really be computed using interval arithmetic too!
def remainder(x, n):
xi = max(0, x)
r = exp(xi) / factorial(n+1)
r = r * x**(n+1)
return abs(r)
def exponential(x, n):
"""
Compute exp(x) using n terms of the Taylor series for exp using
intervals, and print detailed error analysis.
"""
t = taylor(x, n)
r = remainder(x, n)
expx = exp(x)
print("Correct value of exp(x): ", expx)
print()
print("Computed interval: ")
print(t)
print()
print("Computed value (midpoint): ", t.mid)
print()
print("Estimated rounding error: ", t.delta)
print("Estimated truncation error: ", r)
print("Estimated total error: ", t.delta + r)
print("Actual error ", abs(expx - t.mid))
print()
u = t + mpi(-r, r)
print("Interval with est. truncation error added:")
print(u)
print()
print("Correct value contained in computed interval:", t.a <= expx <= t.b)
print("When accounting for truncation error:", u.a <= expx <= u.b)
if __name__ == "__main__":
print("Interval arithmetic demo")
print()
print("This script sums the Taylor series for exp(x) using interval arithmetic,")
print("and then compares the numerical errors due to rounding and truncation.")
print()
x = mpf(input("Enter the value of x (e.g. 3.5): "))
n = int(input("Enter the number of terms n (e.g. 10): "))
print()
exponential(x, n)