orangeduck / Corange

Pure C Game Engine
http://www.youtube.com/watch?v=482GxqTWXtA
Other
1.78k stars 199 forks source link

Is the "quadratic()" function being properly calculated? #68

Closed d4v3y5c0n3s closed 3 years ago

d4v3y5c0n3s commented 3 years ago

I recently asked another question about the "quadratic()" function, but I have another one about the implementation. This function obviously lets one use the quadratic formula, which is x = (-b +- sqrt(b^2 - 4 a c))/2a. Please see this Khan Academy if my quadratic formula is unclear. This is almost reflected in the code, but instead of "2a," it appears to divide the discriminant by just "2." Why is this? I'm fairly new to computer graphics math, so I am unsure if this is intentional or not.

Here is the code from Corange that I'm asking about, with the parts I'm curious about followed by a comment. `bool quadratic(float a, float b, float c, float t0, float t1) {

float descrim = bb - 4a*c;

if (descrim < 0) {

return false;

} else {

float d = sqrtf(descrim);
float q = (b < 0) ? (-b - d) / 2.0 : (-b + d) / 2.0;//  Should "2.0" be changed to "2.0*a"?

*t0 = q / a;
*t1 = c / q;

return true;

}

}`

orangeduck commented 3 years ago

Interesting - I can't actually remember where I got this formulation from.

I can see that in the end t0 = q / a so the final value of the first solution is getting divided by a - just one step after it has been divided by 2. However I can't remember how or why the second solution t1 can be derived as being c / q in this case.

d4v3y5c0n3s commented 3 years ago

@orangeduck Yea, I know t0 & t1 are used to calculate the "time" struct parameter in cphysics, but I don't know how this works. Can you point me to any resources that you used when developing this? I want to understand the math here if possible.

orangeduck commented 3 years ago

After a bit more poking around it looks like I am using what is essentially this formulation:

https://math.stackexchange.com/a/2007723

Where q = x_1 * a. In my code t0 and t1 correspond to the two different solutions which on this page are denoted x_1 and x_2.

d4v3y5c0n3s commented 3 years ago

@orangeduck thank you for the article, now it makes a bit more sense what's going on in the code here. Should I close the issue, or leave it open for others to see?

orangeduck commented 3 years ago

Thanks, I will close it!