public void TestAlmostEquals_ComplexMatrix() { ComplexMatrix a1 = ComplexMatrix.Random(3, 2, new ContinuousUniformDistribution()); ComplexMatrix a2 = a1.Clone(); ComplexMatrix b = -a1; ComplexMatrix c = a1 * (1.0 + (1e+10 * Number.PositiveEpsilonOf(1.0))); ComplexMatrix d = a1 * (1.0 + (2 * Number.PositiveEpsilonOf(1.0))); Helper_TestAlmostEqualityForGenericType(a1, a2, b, c, d); // Wrapper Assert.That(ComplexMatrix.AlmostEqual(a1, c), Is.False); Assert.That(ComplexMatrix.AlmostEqual(a1, c, 1e-10), Is.False); Assert.That(ComplexMatrix.AlmostEqual(a1, c, 1e-2), Is.True); // reference type -> no boxing Assert.That(a1, Is.SameAs(a1)); // transpose Assert.That(a1.Transpose(), Is.Not.EqualTo(a1)); Assert.That(Number.AlmostEqual(a1, a1.Transpose()), Is.False); Assert.That(Number.AlmostEqual(a1, a1.Transpose(), 1e-10), Is.False); // hermitian transpose Assert.That(a1.HermitianTranspose(), Is.Not.EqualTo(a1)); Assert.That(Number.AlmostEqual(a1, a1.HermitianTranspose()), Is.False); Assert.That(Number.AlmostEqual(a1, a1.HermitianTranspose(), 1e-10), Is.False); }
AlmostEqual( Vector u, Vector v, double maximumRelativeError) { return(Number.AlmostEqual(u, v, maximumRelativeError)); }
/// <summary> /// Adaptive approximation of the definite integral in the provided interval by the trapezium rule. /// </summary> public double IntegrateAdaptive( CustomFunction f, double intervalBegin, double intervalEnd, double targetRelativeError) { int numberOfPartitions = 1; double step = intervalEnd - intervalBegin; double sum = 0.5 * step * (f(intervalBegin) + f(intervalEnd)); for (int k = 0; k < 20; k++) { double midpointsum = 0; for (int i = 0; i < numberOfPartitions; i++) { midpointsum += f(intervalBegin + ((i + 0.5) * step)); } midpointsum *= step; sum = 0.5 * (sum + midpointsum); step *= 0.5; numberOfPartitions *= 2; if (Number.AlmostEqual(sum, midpointsum, targetRelativeError)) { break; } } return(sum); }
public void Priority_OfACircleEvent_ShouldMatchThePriorityCalculatedByTrigonometry (CircleEvent circle) { // Fixture setup var a = circle.LeftArc.Site.Position; var b = circle.MiddleArc.Site.Position; var c = circle.RightArc.Site.Position; var center = (a - b).CrossMultiply(c - b).Normalize(); var colatitudeOfCenter = Trig.InverseCosine(center[2]); var radius = Trig.InverseCosine(a.ScalarMultiply(center)); var isOnOutsideOfSphere = colatitudeOfCenter + radius <= Constants.Pi; var sign = isOnOutsideOfSphere ? 1 : -1; var expectedPriority = sign * (1 + Trig.Cosine(colatitudeOfCenter + radius)); // Exercise system var priority = circle.Priority; // Verify outcome var failureString = String.Format( "Expected priority was {0}\nActual priority was {1}", expectedPriority, priority); Assert.True(Number.AlmostEqual(expectedPriority, priority, Tolerance), failureString); // Teardown }
public void Priority_OfACircleThrough0N45EAnd45N0EAnd0N45W_ShouldBeCorrect() { // Fixture setup var arcA = new Arc { Site = Utilities.SiteAt(90, 45) }; var arcB = new Arc { Site = Utilities.SiteAt(45, 0) }; var arcC = new Arc { Site = Utilities.SiteAt(90, -45) }; var circle = new CircleEvent(arcA, arcB, arcC); // Exercise system var result = circle.Priority; // Verify outcome var expectedResult = -Trig.Cosine(Trig.DegreeToRadian(135)) - 1; Debug.WriteLine(expectedResult); var failureString = String.Format("Priority was {0}", result); Assert.True(Number.AlmostEqual(result, expectedResult, Tolerance), failureString); // Teardown }
public void Priority_OfACircleThrough0N90WAnd90NAnd0N90E_ShouldBe0() { // Fixture setup var arcA = new Arc { Site = Utilities.SiteAt(90, -90) }; var arcB = new Arc { Site = Utilities.SiteAt(0, 0) }; var arcC = new Arc { Site = Utilities.SiteAt(90, 90) }; var circle = new CircleEvent(arcA, arcB, arcC); // Exercise system var result = circle.Priority; // Verify outcome var expectedResult = 0; var failureString = String.Format("Priority was {0}", result); Assert.True(Number.AlmostEqual(result, expectedResult, Tolerance), failureString); // Teardown }
public static Vector3 LeftIntersection(this IArc arc, Sweepline sweepline) { var p = arc.LeftNeighbour.Position; var q = arc.Site.Position; var Z = sweepline.Z; if (Vector.AlmostEqual(p, q)) { return(AngleUtilities.EquatorialDirection(p)); } if (Number.AlmostEqual(Z, p.Z) && Number.AlmostEqual(Z, q.Z)) { return(AngleUtilities.EquatorialMidpoint(p, q)); } var A = p.X * (Z - q.Z) - q.X * (Z - p.Z); var B = p.Y * (Z - q.Z) - q.Y * (Z - p.Z); var C = (p.Z - q.Z) * Math.Sign(sweepline.Priority) * Math.Sqrt(1 - Z * Z); var A2PlusB2MinusC2 = Math.Max(A * A + B * B - C * C, 0); var x = (A * C + B * Math.Sqrt(A2PlusB2MinusC2)) / (A * A + B * B); var y = (B * C - A * Math.Sqrt(A2PlusB2MinusC2)) / (A * A + B * B); return(new Vector3(x, y, 0)); }
public void LeftIntersection_WhenFociiAreAboveSweepline_ShouldReturnAVectorWhichWhenMappedToAPointOnTheArcIsEquidistantFromBothSites (Arc arc, Sweepline sweepline) { // Fixture setup var focus = arc.Site.Position; var leftFocus = arc.LeftNeighbour.Position; // Exercise system var directionOfIntersection = arc.LeftIntersection(sweepline); var intersection = arc.PointAt(directionOfIntersection, sweepline); // Verify outcome var distanceFromSite = Trig.InverseCosine(focus.ScalarMultiply(intersection)); var distanceFromLeftSite = Trig.InverseCosine(leftFocus.ScalarMultiply(intersection)); var failureString = String.Format("Direction of intersection: {0},\n" + "Intersection: {1},\n" + "Distance from site: {2},\n" + "Distance from left site: {3}", directionOfIntersection, intersection, distanceFromSite, distanceFromLeftSite); Assert.True(Number.AlmostEqual(distanceFromSite, distanceFromLeftSite, Tolerance), failureString); // Teardown }
ProbabilityDensity( double x ) { if (Number.AlmostEqual(0.0, x)) { if (1 == _alpha) { return(double.PositiveInfinity); } if (2 == _alpha) { return(1.0); } return(0.0); } double ln1 = Math.Log(x); double ln2 = Math.Log(_alpha * x + _beta); return(Math.Exp( _pdfScaleLn + _pdfExponent1 * ln1 + _pdfExponent2 * ln2 )); }
public void TestAlmostEquals_Complex() { Complex a1 = new Complex(1.0, 2.0); Complex a2 = new Complex(1.0, 2.0); Complex b = new Complex(2.0, 1.0); Complex c = new Complex(1.0 + 1e+10 * Number.PositiveEpsilonOf(1.0), 2.0); Complex d = new Complex(1.0 + 2 * Number.PositiveEpsilonOf(1.0), 2.0); Helper_TestAlmostEqualityForGenericType(a1, a2, b, c, d); // Wrapper Assert.That(Complex.AlmostEqual(a1, c), Is.False); Assert.That(Complex.AlmostEqual(a1, c, 1e-10), Is.False); Assert.That(Complex.AlmostEqual(a1, c, 1e-2), Is.True); // value type -> boxing Assert.That(a1, Is.Not.SameAs(a1)); // infinity Assert.That(a1, Is.Not.EqualTo(Complex.Infinity)); Assert.That(Number.AlmostEqual(a1, Complex.Infinity), Is.False); Assert.That(Number.AlmostEqual(a1, Complex.Infinity, 1e-10), Is.False); // NaN Assert.That(a1, Is.Not.EqualTo(Complex.NaN)); Assert.That(Number.AlmostEqual(a1, Complex.NaN), Is.False); Assert.That(Number.AlmostEqual(a1, Complex.NaN, 1e-10), Is.False); }
public void TestAlmostEqual() { IFormatProvider format = System.Globalization.CultureInfo.InvariantCulture; double max = double.MaxValue; double min = double.MinValue; Assert.IsTrue(Number.AlmostEqual(0.0, 0.0, 0), "A"); Assert.IsTrue(Number.AlmostEqual(0.0, 0.0, 50), "B"); Assert.IsTrue(Number.AlmostEqual(max, max, 0), "C"); Assert.IsTrue(Number.AlmostEqual(min, min, 0), "D"); Assert.IsFalse(Number.AlmostEqual(0.0, 0.0 + double.Epsilon, 0), "E"); Assert.IsTrue(Number.AlmostEqual(0.0, 0.0 + double.Epsilon, 1), "F"); Assert.IsFalse(Number.AlmostEqual(max, max - 2 * Number.EpsilonOf(max), 0), "G"); Assert.IsFalse(Number.AlmostEqual(max, max - 2 * Number.EpsilonOf(max), 1), "H"); Assert.IsTrue(Number.AlmostEqual(max, max - 2 * Number.EpsilonOf(max), 2), "I"); Assert.IsTrue(Convert.ToDouble("3.170404", format) == 3.170404, "J"); Assert.IsFalse(Convert.ToDouble("4.170404", format) == 4.170404, "K"); Assert.IsTrue(Number.AlmostEqual(Convert.ToDouble("3.170404", format), 3.170404, 0), "L"); Assert.IsFalse(Number.AlmostEqual(Convert.ToDouble("4.170404", format), 4.170404, 0), "M"); Assert.IsTrue(Number.AlmostEqual(Convert.ToDouble("4.170404", format), 4.170404, 1), "N"); Assert.IsFalse(Number.AlmostEqual(double.NaN, double.NaN, 25), "O"); Assert.IsFalse(Number.AlmostEqual(double.PositiveInfinity, double.NegativeInfinity, 25), "P"); Assert.IsTrue(Number.AlmostEqual(double.PositiveInfinity, double.PositiveInfinity, 25), "Q"); }
public void TestDiscreteKalmanFilter() { // Test constants double r = 30.0; // Measurement covariance double T = 20.0; // Time interval between measurements double q = 0.1; // Plant noise constant double tol = 0.0001; // Accuracy tolerance // Reference values to test against (generated from a known filter) // Reference Measurements double[] zs = { 290.16851039, 654.55633793, 968.97141280, 1325.09197161, 1636.35947675, 1974.39053148, 2260.80770553, 2574.36119750, 2901.32285462, 3259.14709098 }; // Expected position estimates (predictions) double[] posp = { 1018.94416547, 1237.00029618, 1754.97092716, 1855.62596430, 2400.27521403, 2446.47067625, 2978.94381631, 3173.63724675 }; // Expected velocity estimates (predictions) double[] velp = { 18.21939138, 13.38351136, 21.52280841, 10.92729947, 21.32868461, 9.24370334, 20.26482836, 13.59419761 }; // Expected position estimates (after measurement update) double[] posu = { 969.33006892, 1324.51475894, 1637.07997492, 1973.70152187, 2261.59660945, 2573.64724909, 2901.75329465, 3258.67447647 }; // Expected velocity estimates (after measurement update) double[] velu = { 13.38351136, 21.52280841, 10.92729947, 21.32868461, 9.24370334, 20.26482836, 13.59419761, 20.93270702 }; // Initial estimate based on two point differencing double z0 = zs[0]; double z1 = zs[1]; Matrix x0 = new Matrix(2, 1); x0[0, 0] = z1; x0[1, 0] = (z1 - z0) / T; Matrix P0 = new Matrix(2, 2); P0[0, 0] = r; P0[1, 0] = r / T; P0[0, 1] = r / T; P0[1, 1] = 2 * r / (T * T); // Setup a DiscreteKalmanFilter to filter DiscreteKalmanFilter dkf = new DiscreteKalmanFilter(x0, P0); double[] aF = { 1d, 0d, T, 1 }; double[] aG = { (T * T) / 2d, T }; Matrix F = new Matrix(aF, 2); // State transition matrix Matrix G = new Matrix(aG, 2); // Plant noise matrix Matrix Q = new Matrix(1, 1); Q[0, 0] = q; // Plant noise variance Matrix R = new Matrix(1, 1); R[0, 0] = r; // Measurement variance matrix Matrix H = new Matrix(1, 2); H[0, 0] = 1d; H[0, 1] = 0d; // Measurement matrix // Test the performance of this filter against the stored data from a proven // Kalman Filter of a one dimenional tracker. for (int i = 2; i < zs.Length; i++) { // Perform the prediction dkf.Predict(F, G, Q); // Test against the prediction state/covariance Assert.IsTrue(Number.AlmostEqual(dkf.State[0, 0], posp[i - 2], tol), "State Prediction (" + i + ")"); Assert.IsTrue(Number.AlmostEqual(dkf.State[1, 0], velp[i - 2], tol), "Covariance Prediction (" + i + ")"); // Perform the update Matrix z = new Matrix(1, 1, zs[i]); dkf.Update(z, H, R); // Test against the update state/covariance // Test against the prediction state/covariance Assert.IsTrue(Number.AlmostEqual(dkf.State[0, 0], posu[i - 2], tol), "State Prediction (" + i + ")"); Assert.IsTrue(Number.AlmostEqual(dkf.State[1, 0], velu[i - 2], tol), "Covariance Prediction (" + i + ")"); } }
Normalize() { double norm = Norm(); if (Number.AlmostEqual(0.0, norm)) { return(Clone()); } return(Scale(1 / norm)); }
public static bool UnorderedEquals(IEnumerable <double> expected, IEnumerable <double> actual, double relativeAccuracy) { var expectedList = expected.ToList(); var actualList = actual.ToList(); var missingFromActual = expectedList.Where(x => expectedList.Count(y => Number.AlmostEqual(x, y, relativeAccuracy)) != actualList.Count(y => Number.AlmostEqual(x, y, relativeAccuracy))); var missingFromExpected = actualList.Where(x => expectedList.Count(y => Number.AlmostEqual(x, y, relativeAccuracy)) != actualList.Count(y => Number.AlmostEqual(x, y, relativeAccuracy))); return(!(missingFromActual.Any() || missingFromExpected.Any())); }
Interpolate( double t ) { if (null == _samples) { throw new InvalidOperationException(Resources.InvalidOperationNoSamplesProvided); } const double tiny = 1.0e-15; int closestIndex; int offset = SuggestOffset(t, out closestIndex); double[] c = new double[_effectiveOrder]; double[] d = new double[_effectiveOrder]; int ns = closestIndex - offset; if (Number.AlmostEqual(_samples.GetT(closestIndex), t)) { return(_samples.GetX(closestIndex)); } for (int i = 0; i < _effectiveOrder; i++) { c[i] = _samples.GetX(offset + i); d[i] = c[i] + tiny; // prevent rare zero-over-zero condition } double x = _samples.GetX(offset + ns--); for (int level = 1; level < _effectiveOrder; level++) { for (int i = 0; i < _effectiveOrder - level; i++) { double hp = _samples.GetT(offset + i + level) - t; double ho = (_samples.GetT(offset + i) - t) * d[i] / hp; double den = ho - c[i + 1]; if (Number.AlmostZero(den)) { // BUGBUG: check - positive or negative infinity? return(double.PositiveInfinity); } den = (c[i + 1] - d[i]) / den; d[i] = c[i + 1] * den; c[i] = ho * den; } x += (2 * (ns + 1) < (_effectiveOrder - level) ? c[ns + 1] : d[ns--]); } return(x); }
public override bool Matches(object actual) { base.actual = actual; if (_maximumRelativeError.HasValue) { return(Number.AlmostEqual(_expected, Convert.ToDouble(actual), _maximumRelativeError.Value)); } return(Number.AlmostEqual(_expected, Convert.ToDouble(actual))); }
/// <summary> /// Determines whether the specified parameters is valid. /// </summary> /// <returns> /// <see langword="true"/> if the probabilities sum up to 1; otherwise, <see langword="false"/>. /// </returns> public bool IsValidParameterSet(int offset, params double[] probabilityMass) { double sum = 0.0; for (int i = 0; i < probabilityMass.Length; i++) { sum += probabilityMass[i]; } return(Number.AlmostEqual(1.0, sum, 10 + 2 * probabilityMass.Length)); }
/// <summary> /// Checks whether two Buckets are equal. /// </summary> public override bool Equals(object obj) { if (!(obj is Bucket)) { return(false); } Bucket b = (Bucket)obj; return(Number.AlmostEqual(this.lowerBound, b.lowerBound) && Number.AlmostEqual(this.upperBound, b.upperBound) && Number.AlmostEqual(this.depth, b.depth)); }
public void Vectors_ShouldAllBeOfUnitLength(Vector3 vector) { // Fixture setup // Exercise system // Verify outcome var result = vector.Norm(); var expectedResult = 1.0; var failureString = String.Format("Had length {0}, expected 1.0", vector); Assert.True(Number.AlmostEqual(result, expectedResult), failureString); // Teardown }
public void Vertices_ShouldAllHaveUnitNorm() { // Fixture setup var icosahedron = IcosahedronFactory.Build(); // Exercise system var vertices = icosahedron.Vertices; // Verify outcome var norms = vertices.Select(vertex => vertex.Position.Norm()).ToArray(); Debug.WriteLine("Norms are " + TestUtilities.CollectionToString(norms)); Assert.True(norms.All(norm => Number.AlmostEqual(norm, 1.0))); // Teardown }
public void Test() { // Fixture setup var arcA = new Arc { Site = Utilities.SiteAt(45, -45) }; var arcB = new Arc { Site = Utilities.SiteAt(0, 0) }; var arcC = new Arc { Site = Utilities.SiteAt(45, 45) }; var circle = new CircleEvent(arcA, arcB, arcC); var a = arcA.Site.Position; var b = arcB.Site.Position; var c = arcC.Site.Position; var center = (a - b).CrossMultiply(c - b).Normalize(); var colatitudeOfCenter = Trig.InverseCosine(center[2]); var radius = Trig.InverseCosine(a.ScalarMultiply(center)); var isOnOutsideOfSphere = colatitudeOfCenter + radius <= Constants.Pi; var sign = isOnOutsideOfSphere ? 1 : -1; var expectedPriority = sign * (1 + Trig.Cosine(colatitudeOfCenter + radius)); // Exercise system var priority = circle.Priority; Debug.WriteLine(expectedPriority); Debug.WriteLine(Trig.RadianToDegree(colatitudeOfCenter)); Debug.WriteLine(Trig.RadianToDegree(radius)); // Verify outcome var failureString = String.Format( "Expected priority was {0}\nActual priority was {1}", expectedPriority, priority); Assert.True(Number.AlmostEqual(expectedPriority, priority, Tolerance), failureString); // Teardown }
Gamma(double a) { if (a > 0.0) { return(Math.Exp(GammaLn(a))); } double reflection = 1.0 - a; double s = Math.Sin(Math.PI * reflection); if (Number.AlmostEqual(0.0, s)) { return(double.NaN); // singularity, undefined } return(Math.PI / (s * Math.Exp(GammaLn(reflection)))); }
public void Vertices_ShouldHaveTheSameLengthsAsTheRadius (IPolyhedronOptions options) { // Fixture setup var polyhedron = GeodesicSphereFactory.Build(options); // Exercise system var vertices = polyhedron.Vertices; // Verify outcome var lengths = vertices.Select(vertex => vertex.Position.Norm()).ToList(); Debug.WriteLine("Lengths were " + TestUtilities.CollectionToString(lengths)); Assert.True(lengths.All(length => Number.AlmostEqual(length, options.Radius))); // Teardown }
Interpolate( double t ) { if (null == _samples) { throw new InvalidOperationException(Resources.InvalidOperationNoSamplesProvided); } int closestIndex; int offset = SuggestOffset(t, out closestIndex); double[] c = new double[_effectiveOrder]; double[] d = new double[_effectiveOrder]; int ns = closestIndex - offset; double den, ho, hp; double x = 0; if (Number.AlmostEqual(_samples.GetT(closestIndex), t)) { return(_samples.GetX(closestIndex)); } for (int i = 0; i < _effectiveOrder; i++) { c[i] = _samples.GetX(offset + i); d[i] = c[i]; } x = _samples.GetX(offset + ns--); for (int level = 1; level < _effectiveOrder; level++) { for (int i = 0; i < _effectiveOrder - level; i++) { ho = _samples.GetT(offset + i) - t; hp = _samples.GetT(offset + i + level) - t; den = (c[i + 1] - d[i]) / (ho - hp); d[i] = hp * den; c[i] = ho * den; } x += (2 * (ns + 1) < (_effectiveOrder - level) ? c[ns + 1] : d[ns--]); } return(x); }
public void Edges_ShouldAllHaveTheSameNorm() { // Fixture setup var icosahedron = IcosahedronFactory.Build(); // Exercise system var edges = icosahedron.Edges; // Verify outcome var norms = edges.Select(edge => (edge.A.Position - edge.B.Position).Norm()).ToArray(); var expectedNorm = norms.First(); Debug.WriteLine("Norms are " + TestUtilities.CollectionToString(norms)); Assert.True(norms.All(norm => Number.AlmostEqual(norm, expectedNorm))); // Teardown }
IsValidParameterSet( int offset, params double[] probabilityMass) { if (null == probabilityMass) { throw new ArgumentNullException("probabilityMass"); } double sum = 0.0; for (int i = 0; i < probabilityMass.Length; i++) { sum += probabilityMass[i]; } return(Number.AlmostEqual(1.0, sum, 10 + (2 * probabilityMass.Length))); }
public void PointAt_ShouldReturnAPointWithTheSameAzimuthAsTheArgument (Arc arc, Vector3 vector, Sweepline sweepline) { // Fixture setup // Exercise system var point = arc.PointAt(vector, sweepline); // Verify outcome var argumentAzimuth = Trig.InverseTangentFromRational(vector.Y, vector.X); var resultAzimuth = Trig.InverseTangentFromRational(point.Y, point.X); var failureString = String.Format("Argument azimuth was {0} \nResult azimuth was {1}", argumentAzimuth, resultAzimuth); Assert.True(Number.AlmostEqual(argumentAzimuth, resultAzimuth, Tolerance), failureString); // Teardown }
public static bool IsConstantAlmost(Expression term, double expected) { if (term.NodeType == ExpressionType.Convert) { // TODO: do we need 'while' instead of 'if' here? UnaryExpression conv = (UnaryExpression)term; term = conv.Operand; } if (term.NodeType != ExpressionType.Constant) { return(false); } ConstantExpression constExpr = (ConstantExpression)term; return(Number.AlmostEqual(Convert.ToDouble(constExpr.Value), expected)); }
public void PointAt_ShouldReturnAPointEquidistantFromTheSweeplineAndTheFocus (Arc arc, Vector3 vector, Sweepline sweepline) { // Fixture setup var focus = arc.Site.Position; // Exercise system var point = arc.PointAt(vector, sweepline); // Verify outcome var distanceToFocus = Trig.InverseCosine(point.ScalarMultiply(focus)); var distanceToSweepline = Math.Abs(sweepline.Colatitude - Trig.InverseCosine(point.Z)); var failureString = String.Format("Distance to focus was {0}\nDistance to sweepline was {1}", distanceToFocus, distanceToSweepline); Assert.True(Number.AlmostEqual(distanceToFocus, distanceToSweepline, Tolerance), failureString); // Teardown }
public void GeodesicDistance_OfAVectorFromTheNorthPole_ShouldEqualItsColatitude (double colatitude, double azimuth) { // Fixture setup var normalizedColatitude = (colatitude % Math.PI + Math.PI) % Math.PI; var vector = VectorUtilities.NewVector(normalizedColatitude, azimuth); var northPole = VectorUtilities.NewVector(0, 0); var expected = normalizedColatitude; // Exercise system var actual = VectorUtilities.GeodesicDistance(northPole, vector); // Verify outcome TestUtilities.WriteExpectedAndActual(expected, actual); Assert.True(Number.AlmostEqual(expected, actual, TestUtilities.RelativeAccuracy)); // Teardown }