Spelunx Cavern SDK
 
Loading...
Searching...
No Matches
MathsUtil.cs
Go to the documentation of this file.
1using System.Collections.Generic;
2using NUnit.Framework;
3using UnityEngine;
4
5namespace Spelunx {
6 /// <summary>
7 /// Utility class for maths functions.
8 /// </summary>
9 public class MathsUtil {
10 private MathsUtil() { }
11
12 /// <summary>
13 /// Solve and quadratic equation in the form ax^2 + bx + c = 0.
14 /// </summary>
15 /// <param name="a">Coefficient of x^2.</param>
16 /// <param name="b">Coefficient of x.</param>
17 /// <param name="c">Constant c.</param>
18 /// <returns>
19 /// Returns an empty list if the equation has no solutions.
20 /// Returns a list with 1 element if the equation has 1 solution.
21 /// Returns a list with 2 elements if the equation has 2 solution.
22 /// </returns>
23 public static List<float> SolveQuadraticEquation(float a, float b, float c) {
24 List<float> solutions = new List<float>();
25
26 // Case 1: The equation has no solution.
27 float determinant = b * b - 4 * a * c;
28 if (determinant < 0.0f) return solutions;
29
30 // Case 2: The equation has 1 solution.
31 float u = (-b - Mathf.Sqrt(b * b - 4.0f * a * c)) / (2.0f * a);
32 if (determinant == 0.0f) {
33 solutions.Add(u);
34 return solutions;
35 }
36
37 // Case 3: The equation has 2 solutions.
38 float v = (-b + Mathf.Sqrt(b * b - 4.0f * a * c)) / (2.0f * a);
39 solutions.Add(Mathf.Min(u, v)); // Sort the solutions.
40 solutions.Add(Mathf.Max(u, v));
41 return solutions;
42 }
43 }
44}
Utility class for maths functions.
Definition: MathsUtil.cs:9
static List< float > SolveQuadraticEquation(float a, float b, float c)
Solve and quadratic equation in the form ax^2 + bx + c = 0.
Definition: MathsUtil.cs:23