Skip to content

Commit

Permalink
Improve WithinTolerance method (transferred from Unit Tests)
Browse files Browse the repository at this point in the history
  • Loading branch information
Stuart88 committed Jun 16, 2020
1 parent 12b7de2 commit dd51f03
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 32 deletions.
32 changes: 3 additions & 29 deletions University Physics Tests/Helpers.cs
@@ -1,41 +1,15 @@
using System;
using UniversityPhysics.Maths;
using UniversityPhysics.Maths;

namespace UniversityPhysics_Tests
{
public static class Helpers
{
#region Public Fields

/// <summary>
/// Percentage of allowed difference when accounting for floating point errors
/// </summary>
public const double tolerance = 0.5;

#endregion Public Fields

// percent

#region Public Methods

public static bool WithinTolerance(double result, double expected)
public static bool WithinTolerance(double a, double b)
{
//basic check. Necessary for case where result == expected == 0
if (result == expected)
return true;

//force both into positive values, so 'highest' (below) is not 0;
//necessary to prevent DivideByZero issue when dividing be 'highest'
result = Math.Abs(result);
expected = Math.Abs(expected);

double highest = Math.Max(result, expected);

double diff = Math.Abs(result - expected);

double percentOff = ((diff / highest) * 100);

return percentOff < tolerance;
return MathsHelpers.WithinTolerance(a, b);
}

public static bool WithinTolerance(Vector result, Vector expected)
Expand Down
23 changes: 20 additions & 3 deletions University Physics/Maths/MathsHelpers.cs
Expand Up @@ -9,9 +9,9 @@ public static class MathsHelpers
#region Private Fields

/// <summary>
/// For value comparison. Necessary for avoiding floating point accurary errors
/// Percentage of allowed difference when accounting for floating point errors
/// </summary>
private const double tolerance = 0.0000001;
public const double Tolerance = 0.5;

#endregion Private Fields

Expand Down Expand Up @@ -80,7 +80,24 @@ public static double DistanceTo(this Vector v1, Vector v2)

public static bool WithinTolerance(double a, double b)
{
return Math.Abs(a - b) <= tolerance;
//basic check.
if (a == b)
return true;

// Convert both into positive values.
// This ensures the higher of the two values is always the denominator
// in division below, to prevents a DivideByZero exception.

a = Math.Abs(a);
b = Math.Abs(b);

double highest = Math.Max(a, b);

double diff = Math.Abs(a - b);

double percentOff = (diff / highest) * 100;

return percentOff < Tolerance;
}

public static double ToDegrees(double radians)
Expand Down

0 comments on commit dd51f03

Please sign in to comment.