Euler method in c++; Values getting too big too fast - c++

i am trying to solve the equation of motion for a particle with mass m attached to a spring with a spring constant k. Both are set to 1 however.
The algorithm looks like this:
My (attempted) solution, written in c++, looks like this:
#include <iostream>
#include <iomanip>
#include <math.h>
#include <stdlib.h>
#include <fstream>
// Initialise file to write series of values in
std::ofstream output("Eulermethod.txt");
// Define Euler algorithm
void euler(double x_0, double v_0, double delta, double t_max) {
double x_prev = x_0;
double v_prev = v_0;
double x_new, v_new;
for (double t = 0; t < t_max; t = t + delta) {
x_new = x_prev + t * v_prev;
v_new = v_prev - t * x_prev;
// Writes time, position and velocity into a csv file
output << std::fixed << std::setprecision(3) << t << "," << x_prev << "," << v_prev << std::endl;
x_prev = x_new;
v_prev = v_new;
// Breaks loop if values get to big
if ((x_new != x_new) || (v_new != v_new) || (std::isinf(x_new) == true) || (std::isinf(v_new) == true)) {
break;
}
}
}
int main() {
// Initialize with user input
double x_0, v_0, t_max, delta;
std::cout << "Initial position x0?: ";
std::cin >> x_0;
std::cout << "Intial velocity v0?: ";
std::cin >> v_0;
std::cout << "Up to what time t_max?: ";
std::cin >> t_max;
std::cout << "Step size delta?: ";
std::cin >> delta;
// Runs the function
euler(x_0, v_0, delta, t_max);
}
I know that the solution will grow indefinitely but for smaller values of t it should resemble the analytical solution while growing slowly.
The values i get are blowing out of proportions after ca. 10 iterations and i can not find out why.
When i plot the position as a function of the time i get the plot below, which is obviously wrong.

Your equation implementation is wrong. You are usint t instead of dt. Correct variant:
x_new = x_prev + delta * v_prev;
v_new = v_prev - delta * x_prev;
And a side note if you plan to develop your code further: common approach to implementation of ODE solver is to have a method with signature similar to
Output = solveOde(System, y0, t);
Where System is method that describes the ODE dy/dx = f(x,t), e.g.
std::vector<double> yourSystem(std::vector<double> y, double /*t unused*/)
{
return {y[1], -y[0]};
}
y0 are initial conditions, and t is a time vector (delta is calculated internally). Take a look at boost odeint or more compact and transparent python documentation.

Related

Specific right-angled Triangles are not being recognized as right-angled in Cpp

I have to take the coordinates of the vertices of a triangle from the user and tell if it is a right-angled triangle or not. I'm using Pythagoras Theorem to Find out i.e. h * h = b * b + p * p
But surprisingly this doesn't work for some specific right-angled triangles.
Here is one such Triangle:
Vertex A: (x, y) = (1, 3)
Vertex B: (x, y) = (1, 1)
Vertex C: (x, y) = (5, 1)
It calculates perfectly, which I figured out by printing the calculation, but still doesn't work.
Then I tried by using sqrt() function from the cmath library this way:
h = sqrt(b * b + p * p)
Logically it is the same, but it worked.
I want to understand, why the earlier method is not working?
Here is a simplified version of My Code:
#include <iostream>
#include <cmath>
using namespace std;
class Vertex {
double x, y;
public:
void take_input(char obj) {
cout << endl << " Taking Coordinates of Vertex " << obj << ": " << endl;
cout << " Enter the x component: ";
cin >> x;
cout << " Enter the y component: ";
cin >> y;
}
double distance(Vertex p) {
double dist = sqrt((x-p.x)*(x-p.x) + (y-p.y)*(y-p.y));
return dist;
}
};
class Triangle {
Vertex a, b, c;
public:
void take_inp(string obj) {
cout << endl << "Taking Vertices of the Triangle " << obj << ": " << endl;
cout << " Verteces should be in a counter clockwise order (as per convention)." << endl;
a.take_input('A');
b.take_input('B');
c.take_input('C');
}
void is_rt_ang() {
double h = a.distance(c)*a.distance(c);
double bp = a.distance(b)*a.distance(b) + b.distance(c)*b.distance(c);
/*
// Strangely this attempt works which is logically the same:
double h = a.distance(c);
double bp = sqrt(a.distance(b)*a.distance(b) + b.distance(c)*b.distance(c));
*/
if (h == bp) {
cout << "Angle is 90" << endl;
cout << h << " = " << bp << endl;
cout << "It is Right-Angled" << endl;
}
else {
cout << "Angle is not 90!" << endl;
cout << h << " != " << bp << endl;
cout << "It is Not a Right-Angled" << endl;
}
}
};
int main()
{
Triangle tri1, tri2;
tri1.take_inp("tri1");
tri1.is_rt_ang();
return 0;
}
The line
double dist = sqrt((x-p.x)*(x-p.x) + (y-p.y)*(y-p.y));
in the Vertex::distance method gives you an approximation of a square root which is rarely going to coincide with an exact answer. This is because most real numbers can't be represented in floating point arithmetic.
But in given code sample you can make do without sqrt. Replace Vertex::distance method with a method
double distance_square(Vertex p) {
double dist_square = (x-p.x)*(x-p.x) + (y-p.y)*(y-p.y);
return dist_square;
}
and call it like this in Triangle::is_rt_ang:
double h = a.distance_square(c);
double bp = a.distance_square(b) + b.distance_square(c);
This solution is still flawed because floating-point multiplication is also a subject to rounding errors. But if it is guaranteed that you are going to work only with integer coordinates, you can replace all doubles in your code with ints and for them there is no problem with multiplication (besides possibly going out of bounds for large numbers).
EDIT: Also a comment on printing
It calculates perfectly, which I figured out by printing the
calculation, but still doesn't work.
When you print doubles you need to set precision manually in order to avoid rounding. If in your code I replace a line
cout << h << " != " << bp << endl;
with
cout << std::setprecision(std::numeric_limits<double>::digits10) << std::fixed << h << " != " << bp << endl;
then for example triangle from the question I get the output
Angle is not 90!
20.000000000000004 != 20.000000000000000
It is Not a Right-Angled
For this to compile you will need to add #include <limits> and #include <iomanip>.
In your is_rt_ang function you're assuming that your hypotenuse is always going to be the edge AC, but it doesn't seem like you're doing anything to verify this.
double h = a.distance(c)*a.distance(c);
double bp = a.distance(b)*a.distance(b) + b.distance(c)*b.distance(c);
You could try getting the squares of all your distances first, (AC)^2, (AB)^2, and (BC)^2, then finding the candidate for hypotenuse by taking the max value out of the three, then do something like:
bool isRightTriangle = max == (min1 + min2)
You may also be running into some kind of round-off error with floating point numbers. It is common to use a an epsilon value when comparing floating point numbers because of the inherent round-off errors with them. If you don't need floating point values maybe use an integer, or if you do need floating point values try using an epsilon value in your equalities like:
abs(h - bp) <= epsilon
You should be able to find more information about floating point values, round-off errors, and machine epsilons on the web.
Here is a link to a SO Q/A that talks about floating point math that may be a good resource for you: Is floating point math broken?

Did I use Xcode incorrectly or I wrote the program incorrectly?

So I am doing a C++ question about sine.
It says that sin x can be approximated via the polynomial x-(x^3/6)+(x^5/120)-(x^7/5040), and it tells me to output both the approximated sin value and the sin value calculated via cmath.
The input is in degrees, and we have to first convert it to radians then find out sin.
Sample run (only 45 is the input, other our output):
Angle: 45
approxSin = 0.70710647
cmath sin = 0.70710678
I have attempted to write a code for this. When I pressed command+R, nothing happens despite the program saying "build successful". I am new to Xcode, so I am not sure whether I used Xcode incorrectly or I wrote the program incorrectly. Can anyone help?
#define _USE_MATH_DEFINES
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double approxSin(double angleDeg) {
if (-180<angleDeg<180) return approxSin(angleDeg-(angleDeg*angleDeg*angleDeg)/6+(angleDeg*angleDeg*angleDeg*angleDeg*angleDeg)/120-(angleDeg*angleDeg*angleDeg*angleDeg*angleDeg*angleDeg*angleDeg)/5040);
}
int main(){
float angleDeg;
cin >> angleDeg;
if (angleDeg>180) {
while (angleDeg>180) {
angleDeg = angleDeg-360;
}
} else if (angleDeg<-180) {
while (angleDeg<-180) {
angleDeg = angleDeg+360;
}
}
cout << "approxSin = " << &approxSin << endl;
cout << "cmath sin = " << setprecision(8) << sin(angleDeg);
return 0;
}
my code
My guess about your problem: You run the program, and it patiently waits for your input.
With
cin >> angleDeg;
your program seemingly halts, while it's waiting for you to give some input in the IDE console window. Since you haven't written any prompt there's no output to tell you it's waiting for input.
I suggest you add some output first to ask for the input:
cout << "Please enter angle in degrees: ";
cin >> angleDeg;
When I pressed command+R, nothing happens despite the program saying "build successful".
I guess that the answer by Some programmer dude should solve this issue, but, as noted in the comments, there are much worse problems in the posted code, probably depending by a misunderstanding of how functions should be declared and called in C++.
Consider this:
double approxSin(double angleDeg) {
if (-180<angleDeg<180) return approxSin(/* Some unreadable expression */);
}
It's enough to generate a couple of warning:
prog.cc:7:22: warning: result of comparison of constant 180 with expression of type 'bool'
is always true [-Wtautological-constant-out-of-range-compare]
if (-180&ltangleDeg&lt180) return approxSin(angleDeg-(...));
~~~~~~~~~~~~~^~~~
prog.cc:6:35: warning: all paths through this function will call itself [-Winfinite-recursion]
double approxSin(double angleDeg) {
^
The relational operators are evaluated left-to-right, so that an expressions like -180<angleDeg<180 is read by the compiler as (-180 < angleDeg) < 180. The result of -180 < angleDeg is a bool which leads to the kind warning by the compiler about that expression beeing always true.
It could be written as -180 < angle && angle < 180, but given the OP's assignment, the angle should be tested against plus or minus pi. Also, the alternative branch should be written as well.
The second warning is about the recursive call of the function, which makes no sense, without any alternative path. I can only guess that the OP has misinterpreted how values are returned from a function.
The polynomial itself could be evaluated in a more readable way using std::pow or applying Horner's method. I'll show an example later.
The other big problem (specular, someway) is in the "call" site, which isn't a call at all:
cout << "approxSin = " << &approxSin << endl;
It ends up printing 1 and the reasons can be found in this Q&A: How to print function pointers with cout?
Last, I'd note that while the assignment specifically requires to convert the inputted angle from degrees to radians (as the argument of std::sin is), the posted code only checks the range in degrees, without any conversion.
The following implementation compares different methods for evaluating the sin() function
#define _USE_MATH_DEFINES
#include <iostream>
#include <iomanip>
#include <cmath>
namespace my {
// M_PI while widespread, isn't part of the ISO standard
#ifndef M_PI
constexpr double pi = 3.141592653589793115997963468544185161590576171875;
#else
constexpr double pi = M_PI;
#endif
constexpr double radians_from_degrees(double degrees)
{
return degrees * pi / 180.0;
}
constexpr double convert_angle_to_plus_minus_pi(double angle)
{
while ( angle < -pi )
angle += 2.0 * pi;
while ( angle > pi ) {
angle -= 2.0 * pi;
}
return angle;
}
// Approximates sin(angle), with angle between [-pi, pi], using a polynomial
// Evaluate the polynomial using Horner's method
constexpr double sin_a(double angle)
{
// A radian is passed, but the approximation is good only in [-pi, pi]
angle = convert_angle_to_plus_minus_pi(angle);
// Evaluates p(a) = a - a^3 / 6 + a^5 / 120 - a^7 / 5040
double sq_angle = angle * angle;
return angle * ( 1.0 + sq_angle * (-1.0/6.0 + sq_angle * ( 1.0/120.0 - sq_angle / 5040.0)));
}
double sin_b(double angle) {
angle = convert_angle_to_plus_minus_pi(angle);
return angle - pow(angle, 3) / 6.0 + pow(angle, 5) / 120.0 - pow(angle, 7) / 5040.0;
}
} // End of namespace 'my'
int main()
{
std::cout << " angle std::sin my::sin_a my::sin_b\n"
<< "-----------------------------------------------\n"
<< std::setprecision(8) << std::fixed;
for (int i = -90; i < 475; i += 15)
{
double angle = my::radians_from_degrees(i);
std::cout << std::setw(5) << i
<< std::setw(14) << std::sin(angle)
<< std::setw(14) << my::sin_a(angle)
<< std::setw(14) << my::sin_b(angle) << '\n';
}
return 0;
}

C++ Console - New lat/lon coordinate using azimuth and range [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I would like assistance understanding this code I found during a search. I have been stuck for 2 weeks trying to get it and it's holding my project back. I am honestly trying to learn as I go and not just be a script kiddie about it, but this is much more complicated than the rest of my project even though I am trying. (I just learned about auto today while trying to understand this code, for example.)
I am working on a weather app and I know the lat/lon of the radar site. I need the lat/lon of a feature the radar has detected based off of the azimuth/range that the radar tells me (example, 271 degrees and 7 nautical miles). I need to understand how I can use this code below to convert the azimuth/range to a new lat lon coordinate. I don't require the other functions, just to be able to put my variables (starting coords, azimuth and range) and get a result. The code below looks to do much more than that, and it is confusing me.
I see the following code near the end :
auto coordinate = CoordinateToCoordinate(latitude1, longitude1, angle, meters);
... Which looks to be the part I would need out of this. I see how it's calculating it but once I dig deeper I just get myself confused. I have tried hacking at the code so much that I gave up and don't even have any examples.
I would like to be able to set my variables manually (example cin>>) and have the lat and lon output into a variable that I can save to a text file. I am able to do everything myself (ingesting the starting variables and writing the result to a text file) except the actual conversion itself.
How could I get started with this using the code below?
My example variables are :
Original Latitude = 29.4214
Original Longitude = -98.0142
Azimuth from Origin = 271 degrees
Range from Origin = 6 nautical miles (I can convert to meters if needed,
in this case it's 11112 meters)
The actual unedited code is below and a copy at this link. If I get help with this I won't just copy/paste and I will come back with the completed code after I make it. I really am wanting to understand as I go, so I can be better with these advanced topics and not be constrained in the future. Code below :
#include<iostream>
#include<iomanip>
#include<cmath>
// Source: // http://w...content-available-to-author-only...o.uk/scripts/latlong.html
static const double PI = 3.14159265358979323846, earthDiameterMeters = 6371.0 * 2 * 1000;
double degreeToRadian (const double degree) { return (degree * PI / 180); };
double radianToDegree (const double radian) { return (radian * 180 / PI); };
double CoordinatesToAngle (double latitude1,
const double longitude1,
double latitude2,
const double longitude2)
{
const auto longitudeDifference = degreeToRadian(longitude2 - longitude1);
latitude1 = degreeToRadian(latitude1);
latitude2 = degreeToRadian(latitude2);
using namespace std;
const auto x = (cos(latitude1) * sin(latitude2)) -
(sin(latitude1) * cos(latitude2) * cos(longitudeDifference));
const auto y = sin(longitudeDifference) * cos(latitude2);
const auto degree = radianToDegree(atan2(y, x));
return (degree >= 0)? degree : (degree + 360);
}
double CoordinatesToMeters (double latitude1,
double longitude1,
double latitude2,
double longitude2)
{
latitude1 = degreeToRadian(latitude1);
longitude1 = degreeToRadian(longitude1);
latitude2 = degreeToRadian(latitude2);
longitude2 = degreeToRadian(longitude2);
using namespace std;
auto x = sin((latitude2 - latitude1) / 2), y = sin((longitude2 - longitude1) / 2);
#if 1
return earthDiameterMeters * asin(sqrt((x * x) + (cos(latitude1) * cos(latitude2) * y * y)));
#else
auto value = (x * x) + (cos(latitude1) * cos(latitude2) * y * y);
return earthDiameterMeters * atan2(sqrt(value), sqrt(1 - value));
#endif
}
std::pair<double,double> CoordinateToCoordinate (double latitude,
double longitude,
double angle,
double meters)
{
latitude = degreeToRadian(latitude);
longitude = degreeToRadian(longitude);
angle = degreeToRadian(angle);
meters *= 2 / earthDiameterMeters;
using namespace std;
pair<double,double> coordinate;
coordinate.first = asin((sin(latitude) * cos(meters))
+ (cos(latitude) * sin(meters) * cos(angle)));
coordinate.second = longitude + atan2((sin(angle) * sin(meters) * cos(latitude)),
cos(meters) - (sin(latitude) * sin(coordinate.first)));
coordinate.first = radianToDegree(coordinate.first);
coordinate.second = radianToDegree(coordinate.second);
return coordinate;
}
int main ()
{
using namespace std;
const auto latitude1 = 12.968460, longitude1 = 77.641308,
latitude2 = 12.967862, longitude2 = 77.653130;
cout << std::setprecision(10);
cout << "(" << latitude1 << "," << longitude1 << ") --- "
"(" << latitude2 << "," << longitude2 << ")\n";
auto angle = CoordinatesToAngle(latitude1, longitude1, latitude2, longitude2);
cout << "Angle = " << angle << endl;
auto meters = CoordinatesToMeters(latitude1, longitude1, latitude2, longitude2);
cout << "Meters = " << meters << endl;
auto coordinate = CoordinateToCoordinate(latitude1, longitude1, angle, meters);
cout << "Destination = (" << coordinate.first << "," << coordinate.second << ")\n";
}
I think you just want something like this:
#include <iostream>
std::pair<double,double> CoordinateToCoordinate (double latitude,
double longitude,
double angle,
double meters)
{
...
...
}
using namespace std;
int main() {
double lat, lon, angle, dist;
cout << "Enter lat:"; cin >> lat;
cout << "Enter lon:"; cin >> lon;
cout << "Enter angle:"; cin >> angle;
cout << "Enter dist:"; cin >> dist;
auto coordinate = CoordinateToCoordinate(lat, lon, angle, dist);
cout << "Destination = (" << coordinate.first << "," << coordinate.second << ")\n";
}

atanf gives me wrong answers

I was doing Exercise of Chapter 3 (Functions) from a Book Called C++ Modules for Gaming.
It is this one question I am not able to Do is to find atanf(4/2) of (2,4) which according to the book and my calculator should give back '63.42' degrees.
Instead it gives me 1.107 degrees.
Here is my code:
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
void tani(float a,float b) //Finds the Tan inverse
{
float res;
res = atanf(b / a);
cout << res << endl;
}
int main()
{
cout << "Enter The Points X and Y: " << endl;
float x, y;
cin >> x >> y; //Input
tani(x,y); //calling Function
}
atanf, and the other trigonometric functions in c++ return results in radians. 1.107 radians are 63.426428 degress, so your code is correct.
You can convert radians to degrees by multiplying by 180 and dividing by Pi (the M_PI constant provided by <cmath>):
cout << res * 180.0 / M_PI << endl;
It is giving you correct answer in radians.Simply Convert it to Degree!
void tani(float a, float b) //Finds the Tan inverse
{
float res;
res = atanf(b/ a);
cout << res *(180 / 3.14) << endl;
}

Gas Particle simulation Collision calculation C++

This I feel is a rather complicated problem, I hope I can fit it in to small enough of a space to make it understandable. I'm presently writing code to
simulate Ideal gas particles inside a box. I'm calculating if two particles will collide having calculated the time taken for them to reach their closest point. (using an example where they have head on collision).
In this section of code I need to find if they will collide at all for two particles, before then calculating at what time and how they collide etc.
Thus for my two paricles:
Main.cpp
Vector vp1(0,0,0);
Vector vv1(1,0,0);
Vector vp2(12,0,0);
Vector vv2(-1,0,0);
Particle Particle1(1, vp1, vv1);
Particle Particle2(1, vp2, vv2);
Particle1.timeToCollision(Particle2);
Within my program I define a particle to be:
Header File
class Particle {
private:
Vector p; //position
Vector v; //velocity
double radius; //radius
public:
Particle();
Particle(double r, const Vector Vecp, const Vector Vecv);
void setPosition(Vector);
void setVelocity(Vector);
Vector getPosition() const;
Vector getVelocity() const;
double getRadius() const;
void move(double t);
double timeToCollision(const Particle particle);
void collideParticles(Particle);
~Particle();
};
Vector is another class that in short gives x, y, z values. It also contains multiple functions for manipulating these.
And the part that I need help with, within the .cpp (Ignore the cout start and letters etc, they are simple checks where my code exits for tests.)
Given the equations:
I have already written code to do the dot product and modulus for me and:
where
s is distance travelled in time tac.
double Particle::timeToCollision(const Particle particle){
Vector r2 = particle.getPosition();
Vector r1 = p;
Vector v2 = particle.getVelocity();
Vector v1 = v;
Vector r0 = r2 - r1;
Vector v = v2 - v1;
double modv;
double tca;
double result = 0;
double bsqr;
modv = getVelocity().modulus();
cout << "start" << endl;
if(modv < 0.0000001){
cout << "a" << endl;
result = FLT_MAX;
}else{
cout << "b" << endl;
tca = ((--r0).dot(v)) / v.modulusSqr();
// -- is an overridden operator that gives the negation ( eg (2, 3, 4) to (-2, -3, -4) )
if (tca < 0) {
cout << "c" << endl;
result = FLT_MAX;
}else{
cout << "d" << endl;
Vector s(v.GetX(), v.GetY(), v.GetZ());
s.Scale(tca);
cout << getVelocity().GetX() << endl;
cout << getVelocity().GetY() << endl;
cout << getVelocity().GetZ() << endl;
double radsqr = radius * radius;
double bx = (r0.GetX() * r0.GetX() - (((r0).dot(v)) *((r0).dot(v)) / v.modulusSqr()));
double by = (r0.GetY() * r0.GetY() - (((r0).dot(v)) *((r0).dot(v)) / v.modulusSqr()));
double bz=(r0.GetZ() * r0.GetZ() - (((r0).dot(v)) * ((r0).dot(v)) / v.modulusSqr()));
if (bsqr < 4 * radsqr) {
cout << "e" << endl;
result = FLT_MAX;
} else {
}
cout << "tca: " << tca << endl;
}
}
cout << "fin" << endl;
return result;
}
I have equations for calculating several aspects, tca refers to Time of closest approach.
As written in the code I need to check if b > 4 r^2, I Have made some attempts and written the X, Y and Z components of b out. But I'm getting rubbish answers.
I just need help to establish if I've already made mistakes or the sort of direction I should be heading.
All my code prior to this works as expected and I've written multiple tests for each to check.
Please inform me in a comment for any information you feel I've left out etc.
Any help greatly appreciated.
You had several mistakes in your code. You never set result to a value different from 0 or FLT_MAX. You also never calculate bsqr. And I guess the collision happens if bsqr < 4r^2 and not the other way round. (well i do not understand why 4r^2 instead of r^2 but okay). Since you hide your vector implementation I used a common vector library. I also recommend to not use handcrafted stuff anyway. Take a look into armadillo or Eigen.
Here you go with a try in Eigen.
#include <iostream>
#include <limits>
#include <type_traits>
#include "Eigen/Dense"
struct Particle {
double radius;
Eigen::Vector3d p;
Eigen::Vector3d v;
};
template <class FloatingPoint>
std::enable_if_t<std::is_floating_point<FloatingPoint>::value, bool>
almost_equal(FloatingPoint x, FloatingPoint y, unsigned ulp=1)
{
FloatingPoint max = std::max(std::abs(x), std::abs(y));
return std::abs(x-y) <= std::numeric_limits<FloatingPoint>::epsilon()*max*ulp;
}
double timeToCollision(const Particle& left, const Particle& right){
Eigen::Vector3d r0 = right.p - left.p;
Eigen::Vector3d v = right.v - left.v;
double result = std::numeric_limits<double>::infinity();
double vv = v.dot(v);
if (!almost_equal(vv, 0.)) {
double tca = (-r0).dot(v) / vv;
if (tca >= 0) {
Eigen::Vector3d s = tca*v;
double bb = r0.dot(r0) - s.dot(s);
double radius = std::max(left.radius, right.radius);
if (bb < 4*radius*radius)
result = tca;
}
}
return result;
}
int main()
{
Eigen::Vector3d vp1 {0,0,0};
Eigen::Vector3d vv1 {1,0,0};
Eigen::Vector3d vp2 {12,0,0};
Eigen::Vector3d vv2 {-1,0,0};
Particle p1 {1, vp1, vv1};
Particle p2 {1, vp2, vv2};
std::cout << timeToCollision(p1, p2) << '\n';
}
My apologies for a very poorly worded question that was to long and bulky to make much sense of. Luckily I have found my own answer to be much easier then initially anticipated.
double Particle::timeToCollision(const Particle particle){
Vector r2=particle.getPosition();
Vector r1=p;
Vector v2=particle.getVelocity();
Vector v1=v;
Vector r0=r2-r1;
Vector v=v2-v1;
double modv;
double tca = ((--r0).dot(v)) / v.modulusSqr();
double bsqr;
double result=0;
double rColTestx=r0.GetX()+v.GetX()*tca;
double rColTesty=r0.GetY()+v.GetY()*tca;
double rColTestz=r0.GetZ()+v.GetZ()*tca;
Vector rtColTest(rColTestx, rColTesty, rColTestz);
modv=getVelocity().modulus();
cout << "start " << endl;
if(modv<0.0000001){
cout << "a" << endl;
result=FLT_MAX;
}else{
cout << "b" << endl;
if (tca < 0) {
cout << "c" << endl;
result=FLT_MAX;
}else{
cout << "d" << endl;
Vector s(v.GetX(), v.GetY(), v.GetZ());
s.Scale(tca);
cout << getVelocity().GetX() << endl;
cout << getVelocity().GetY() << endl;
cout << getVelocity().GetZ() << endl;
double radsqr= radius*radius;
bsqr=rtColTest.modulusSqr();
if (bsqr < 4*radsqr) {
cout << "e" << endl;
cout << "collision occurs" << endl;
result = FLT_MAX;
} else {
cout << "collision does not occurs" << endl;
}
}
}
cout << "fin" << endl;
return result;
}
Sorry its a large section of code. Also FLT_MAX is from the cfloat lib. I didn't stat this in my question. I found this to work for several examples I calculated on paper to check.
To be Clear, the return resultand result=0 were arbitrary. I later edit to return time but for this part didn't need or want that.