GeometriCS/utils/Utils.cs

51 lines
2.1 KiB
C#
Raw Permalink Normal View History

namespace GeometriCS
2024-03-02 11:23:42 +01:00
{
/// <summary>
/// Common utilities throughout the library.
/// </summary>
public static class Utils
2024-03-02 11:23:42 +01:00
{
/// <summary>
/// Default precision for double equality comparison.
/// </summary>
private const double DOUBLEPRECISION = 1E-5;
/// <summary>
/// Is this number in the range <lower; higher> (inclusive).
/// </summary>
/// <param name="num">Number to compare</param>
/// <param name="lower">Lower end of the range.</param>
/// <param name="higher">Higher end of the range.</param>
/// <returns><c>true</c>if number is in the range <lower; higher>, <c>false</c> if it is outside.</returns>
public static bool IsInRange(this double num, double lower, double higher)
{
return num >= lower && num <= higher;
}
2024-03-02 11:23:42 +01:00
/// <summary>
/// Tests whether the difference between two doubles is within a given limit.
/// </summary>
/// <param name="a">First value to test.</param>
/// <param name="b">Second value to test.</param>
/// <param name="prec">Maximum allowed difference.</param>
/// <returns>Do the values almost equal each other.</returns>
public static bool DoubleEquals(double a, double b, double prec = DOUBLEPRECISION) => Math.Abs(a - b) <= prec;
/// <summary>
/// Returns the coefficients of a line defined by equation Ax + By + C = 0,
/// given two points that lie on the line.
/// </summary>
/// <param name="pt1">First point on the line.</param>
/// <param name="pt2">Second point on the line.</param>
/// <returns>Touple (Coeff_A, Coeff_B, Coeff_C).</returns>
public static (double A, double B, double C) Line2CoefficientsFromTwoPoints(Vector2d pt1, Vector2d pt2)
{
double coeff_A = pt2.Y - pt1.Y;
double coeff_B = pt1.X - pt2.X;
double coeff_C = (pt1.Y * (pt2.X - pt1.X)) -
(pt1.X * (pt2.Y - pt1.Y));
return (coeff_A, coeff_B, coeff_C);
}
2024-03-02 11:23:42 +01:00
}
}