Reputation: 12423
This seems like an incredibly simple problem to solve, but everything I've found about it has been too complex for me to understand.
I have this basic ballistic equation:
Given that I know v, g, x and y, how would I go about finding theta? It's very easy to read on paper, but I don't know how this would be done in code.
[EDIT #3:] My try (with input from answers below) is this:
gx = g*x
brackets = gx^2 + 2*y*v^2
sqrroot = sqrt( v^4 - g*brackets )
top1 = v^2 + sqrroot
theta1 = atan( top1 / gx )
top2 = v^2 - sqrroot
theta2 = atan( top2 / gx )
Upvotes: 0
Views: 826
Reputation: 153498
A c solution
#include<math.h>
void MattW_f(double *theta_p, double *theta_n, double g, double v, double x, double y) {
double v2 = v*v;
double gx = g*x;
// No check against sqrt(negative number)
double discriminant = sqrt(v2*v2 - g*(gx*x + 2*y*v2));
if (theta_p) {
// atan2() returns -pi to +pi, it is a 4 quadrant arctan.
*theta_p = atan2(v2 + discriminant, gx);
}
if (theta_n) {
*theta_n = atan2(v2 - discriminant, gx);
}
}
Upvotes: 0
Reputation: 51445
More like this.
gx = g*x
brackets = g*x^2 + 2*y*v^2
sqrroot = sqrt( v^4 - g*brackets )
top1 = v^2 + sqrroot
theta1 = atan( top1 / gx )
top2 = v^2 - sqrroot
theta2 = atan( top2 / gx )
You have to account for the plus and the minus in your formula.
You calculate the squares before the multiplication. In some languages, you can calculate g*x^2 by calculating g*x*x.
Upvotes: 1
Reputation: 129507
You're ignoring a solution - you have
top = v^2 + sqrroot
but you also need to do a recalculation with
top = v^2 - sqrroot
to account for the ±
in your equation.
So:
top1 = v^2 + sqrroot
top2 = v^2 - sqrroot
theta1 = atan(top1 / gx)
theta2 = atan(top2 / gx)
(I don't know what equation
is in your code, but I'm assuming you meant top
)
Upvotes: 1
Reputation: 12339
In your last line,
theta = atan( equation / gx )
equation
is not set. You probably want to substituted top
for equation
.
It may also help for you to output each intermediate result (gx, brackets, sqrroot, and top). See if there any unexpected intermediate results.
Upvotes: 0
Reputation: 1136
If you do not have access to the arctan method, you can use a quasi newton algorithm.
Upvotes: 0