/
BrentRootTests.cs
89 lines (78 loc) · 2.84 KB
/
BrentRootTests.cs
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
* Copyright Lamont Granquist, Sebastien Gaggini and the MechJeb contributors
* SPDX-License-Identifier: MIT-0 OR LGPL-2.1+ OR CC0-1.0
*/
using System;
using AssertExtensions;
using MechJebLib.Rootfinding;
using MechJebLib.Utils;
using Xunit;
using static MechJebLib.Utils.Statics;
using static System.Math;
namespace MechJebLibTest.MathsTests
{
public class BrentRootTests
{
[Theory]
[InlineData(2.0)]
[InlineData(2.1)]
[InlineData(2.2)]
[InlineData(2.3)]
[InlineData(2.4)]
[InlineData(2.5)]
[InlineData(2.6)]
[InlineData(2.7)]
[InlineData(2.8)]
[InlineData(2.9)]
public void Test(double a0)
{
double ans = BrentRoot.Solve((t, o) => t * t * t - a0, 0.0, 2.0, null);
ans.ShouldEqual(Pow(a0, 1.0 / 3.0), 10 * EPS);
}
[Fact]
public void TestBracket()
{
// ensure we can find solution at xmin
double ans = BrentRoot.Solve((t, o) => t * t * t, 0.0, 2.0, null);
ans.ShouldBeZero();
// ensure we can find solution at xmax
ans = BrentRoot.Solve((t, o) => t * t * t, -2.0, 0.0, null);
ans.ShouldBeZero();
// this should throw
Exception ex = Assert.Throws<ArgumentException>(() =>
BrentRoot.Solve((t, o) => t * t * t, -2.0, -0.0001, null)
);
Assert.Contains("guess does not bracket the root", ex.Message);
// this should throw
ex = Assert.Throws<ArgumentException>(() =>
BrentRoot.Solve((t, o) => t * t * t, 0.0001, 2, null)
);
Assert.Contains("guess does not bracket the root", ex.Message);
}
[Fact]
public void TestGuess()
{
// this works normally
double ans = BrentRoot.Solve((t, o) => Sin(t), 3, null);
ans.ShouldEqual(PI, EPS2);
// this throws due to not being able to precisely find the root
Exception ex = Assert.Throws<Check.FailedCheck>(() =>
BrentRoot.Solve((t, o) => t * t, 1, null)
);
Assert.Contains("check failed", ex.Message);
// no root at all
ex = Assert.Throws<Check.FailedCheck>(() =>
BrentRoot.Solve((t, o) => Abs(t) + 1, 1, null)
);
Assert.Contains("check failed", ex.Message);
// expansion of region fails to bracket the root
ex = Assert.Throws<Check.FailedCheck>(() =>
BrentRoot.Solve((t, o) => t * t - 0.01, 2, null)
);
Assert.Contains("check failed", ex.Message);
// finds a root even though it shouldn't
ans = BrentRoot.Solve((t, o) => Tan(t), 2, null);
ans.ShouldEqual(PI / 2, 21 * EPS);
}
}
}