-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_high_precision.py
More file actions
70 lines (54 loc) · 2.05 KB
/
Copy pathtest_high_precision.py
File metadata and controls
70 lines (54 loc) · 2.05 KB
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
67
68
69
70
from __future__ import annotations
import mpmath as mp
from scipy.optimize import minimize as scipy_minimize
from mpoptimize import minimize
def test_cobyla_resolves_sub_float_objective_structure() -> None:
with mp.workdps(80):
lower = mp.mpf("5e-30")
upper = mp.mpf("1e-29")
target = mp.mpf("7.5e-30")
def objective(x):
return mp.mpf("1") + (x[0] - target) ** 2
result = minimize(
objective,
x0=[mp.mpf("9.5e-30")],
method="COBYLA",
bounds=[(lower, upper)],
options={"rhobeg": mp.mpf("1e-30"), "tol": mp.mpf("1e-45")},
)
float_result = scipy_minimize(
lambda x: 1.0 + (x[0] - 7.5e-30) ** 2,
x0=[9.5e-30],
method="COBYLA",
bounds=[(5e-30, 1e-29)],
)
mp_error = abs(result.x[0] - target)
float_error = abs(mp.mpf(repr(float_result.x[0])) - target)
assert result.success is True
assert mp.almosteq(result.x[0], target, rel_eps=mp.mpf("1e-20"), abs_eps=mp.mpf("1e-45"))
assert mp_error < float_error
def test_slsqp_resolves_sub_float_objective_structure() -> None:
with mp.workdps(80):
lower = mp.mpf("5e-30")
upper = mp.mpf("1e-29")
target = mp.mpf("7.5e-30")
def objective(x):
return mp.mpf("1") + (x[0] - target) ** 2
result = minimize(
objective,
x0=[mp.mpf("9.5e-30")],
method="SLSQP",
bounds=[(lower, upper)],
options={"ftol": mp.mpf("1e-45")},
)
float_result = scipy_minimize(
lambda x: 1.0 + (x[0] - 7.5e-30) ** 2,
x0=[9.5e-30],
method="SLSQP",
bounds=[(5e-30, 1e-29)],
)
mp_error = abs(result.x[0] - target)
float_error = abs(mp.mpf(repr(float_result.x[0])) - target)
assert result.success is True
assert mp.almosteq(result.x[0], target, rel_eps=mp.mpf("1e-18"), abs_eps=mp.mpf("1e-40"))
assert mp_error < float_error