Jolt Physics
A multi core friendly Game Physics Engine
Loading...
Searching...
No Matches
FindRoot.h
Go to the documentation of this file.
1// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
3// SPDX-License-Identifier: MIT
4
5#pragma once
6
8
12template <typename T>
13inline int FindRoot(const T inA, const T inB, const T inC, T &outX1, T &outX2)
14{
15 // Check if this is a linear equation
16 if (inA == T(0))
17 {
18 // Check if this is a constant equation
19 if (inB == T(0))
20 {
21 if (inC == T(0))
22 {
23 outX1 = outX2 = 0.0f;
24 return 1; // Actually infinitely many solutions
25 }
26
27 return 0;
28 }
29
30 // Linear equation with 1 solution
31 outX1 = outX2 = -inC / inB;
32 return 1;
33 }
34
35 // See Numerical Recipes in C, Chapter 5.6 Quadratic and Cubic Equations
36 T det = DifferenceOfProducts(inB, inB, T(4) * inA, inC);
37 if (det < T(0))
38 return 0;
39 T q = (inB + Sign(inB) * Sqrt(det)) / T(-2);
40 outX1 = q / inA;
41 if (q == T(0))
42 {
43 outX2 = outX1;
44 return 1;
45 }
46 outX2 = inC / q;
47 return 2;
48}
49
#define JPH_NAMESPACE_END
Definition Core.h:433
#define JPH_NAMESPACE_BEGIN
Definition Core.h:427
JPH_NAMESPACE_BEGIN int FindRoot(const T inA, const T inB, const T inC, T &outX1, T &outX2)
Definition FindRoot.h:13
JPH_INLINE constexpr T Sign(T inV)
Get the sign of a value.
Definition Math.h:116
JPH_INLINE float Sqrt(float inV)
Take the square root of a float value.
Definition Math.h:76
JPH_INLINE float DifferenceOfProducts(float inA, float inB, float inC, float inD)
Definition Math.h:49