Velocity & Momentum - I can't go the distance - c++

I am currently working on an assignment that requires me to compile and executie a program with the following parameters:
Write a program that does the following: Calculates the Velocity and Momentum of an object. The formula for the velocity is V=d/t and the formula for Momentum is m=mass*velocity. Your program should consist of two functions: Passing By Values (one), One Passing By Pointers (one). It should also have a for loop and necessary print statements to print the result in a tabular format.
· The Passing By Values function is to calculate the velocity of the object, where you pass two parameters to this function a constant distance, but the time is the value of the for loop: I=1:
double Velocity(double distance,int time);
· The Pass By Pointers function calculates the momentum of the object, where you pass two parameters to this function: The Velocity and a constant mass of an object: mass=100:
double Momentum(double *Velocity,double *mass);
The output should have a tabular format consisting of Time, Velocity, and Momentum. There is no need for a user to enter a value, and the time input should range from 1-200.
** Now here is my struggle, I have put together as much as I can but can't seem to have it compile properly , it just keeps going to "Press any button to continue..."
I truly on't understand what I am doing wrong and just need help to compile and run, any help at all would be appreciated .
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
//Function prototypes (declaring the functions).
double velocity(double distance, int time);
double momentum(double *velocity ,double *mass);
//Main function.
int main()
{
double PrimaryVelo(0);
double TotalMomentum(0);
int t(1);
for (double d = 1; d <= 10; d++)
{
PrimaryVelo = velocity(d, t);
} //End for the primary for loop.
system("pause"); //Prevents closing of debug automatically.
return 0;
} //End of the main function.
//Pass-by-value method for velocity.
double velocity(double distance, int time)
{
return distance / time;
}
//Pass-by-pointers method for momentum.
double momentum(double &velocity ,double &mass)
{
return (velocity * 205);
}

Well....
Here's your code.....
#include <iostream>
using namespace std;
double velocity(double distance, int time);
double momentum(double velocity ,double mass);
int main()
{
double Mass=205;
double Distance=100;
double Velocity;
//cout << "Time\t\tVelocity\tMomentum" << endl; //You'll need to reformat this
for ( int Time = 1 ; Time <= 200 ; Time++ )
{
cout << Time << "\t" ;
cout << velocity ( Distance , Time ) << "\t" ;
Velocity = velocity ( Distance , Time ) ;
cout << momentum ( Velocity , Mass ) << endl ;
}
// If you can't use conio.h and getch();
// Use something like this to stop console from closing itself
int a;
cin>>a;
return 0;
}
double velocity(double distance, int time)
{
return distance / time;
}
double momentum(double velocity ,double mass)
{
return velocity * mass;
}
Note : I've given you code with functions accepting arguments passed by values......
I hope it helps....
Have a nice day....

Related

UPDATED Runge Kutta (RK4) 2nd order DE in C++ ERROR CODE

This is the updated version of Runge Kutta (RK4) 2nd order DE in C++ ERROR CODE
I am still experiencing difficulties with the code. Maybe this has to do with my limited knowledge of Runge-Kutta but when I run this code it doesn't produce an output.
#include <iostream>
#include <cmath>
//dvdt=-(g/L)*sin(theta)
//v=dxdt
double dxdt( double timepassed, double theta )
{
return theta/timepassed;
}
double L;
double g=9.8;
double coeff=-1*(g/L);
double dvdt( double timepassed, double x, double v)
{
return coeff*sin(x);
}
int main(){
// Standard Variables
double theta;
double theta1;
double h = 0.1;
double L;
double timepassed;
double time1;
// Input and Output Printing
std::cout << "Please input initial angle (in decimal radians), length of the pendulum (in meters) and the time desired (in seconds). Click ENTER key after each value."<<"\n";
std::cin >> theta1;
std::cin >> L;
std::cin >> timepassed;
// Specific Variable Declarations
double coeff=-1*(g/L);
double v = dxdt(theta1, timepassed);
double x = theta1;
double d2xdt2 = dvdt(timepassed, theta1, v);
// Defining K Values in Runge Kutta
double kx1,kv1;
double kx2, kv2;
double kx3, kv3;
double kx4, kv4;
double dt;
kx1=dt*dxdt(timepassed,x);
kv1=dt*dvdt(timepassed,x,v);
kx2=dt*dxdt(timepassed+dt/2,x+kx1/2);
kv2=dt*dvdt(timepassed+dt/2,x+kx1/2,v+kv1/2);
kx3=dt*dxdt(timepassed+dt/2,x+kx2/2);
kv3=dt*dvdt(timepassed+dt/2,x+kx2/2,v+kv2/2);
kx4=dt*dxdt(timepassed+dt,x+kx3);
kv4=dt*dvdt(timepassed+dt,x+kx3,v+kv3);
x = x + (1.0/6.0)*(kx1 + 2*kx2 + 2*kx3 + kx4);
v = v + (1.0/6.0)*(kx1 + 2*kv2 + 2*kv3 + kv4);
std::cout << "The angle is" << x; "\n";
std::cout << "The velocity is" << v;
}
Your system equations should be, as it is announced in the comment before it, as
//v=dx/dt
//dv/dt=d2x/dt2=-(g/L)*sin(x), where x=theta
double coeff;
double dxdt( double t, double x, double v) { return v; }
double dvdt( double t, double x, double v) { return coeff*sin(x); }
After the input of the parameters, the number coeff gets computed but not declared anew.
// Specific Variable Declarations
coeff = -(g/L);
Your step size appears to be 0.1. You need to decide what variable name to use, h or dt, and then stay with it.
It is almost certain that you need to perform more than one RK4 step, thus you need to frame them with a loop. What that loop contains in addition to the RK4 stages depends on what the output of the program is supposed to be. Also, you need to adapt the last step if the target time is not a multiple of the time step.
while(t < timepassed) {
kx1=dt*dxdt(t,x,v);
kv1=dt*dvdt(t,x,v);
kx2=dt*dxdt(t+dt/2,x+kx1/2,v+kv1/2);
kv2=dt*dvdt(t+dt/2,x+kx1/2,v+kv1/2);
kx3=dt*dxdt(t+dt/2,x+kx2/2,v+kv2/2);
kv3=dt*dvdt(t+dt/2,x+kx2/2,v+kv2/2);
kx4=dt*dxdt(t+dt,x+kx3,v+kv3);
kv4=dt*dvdt(t+dt,x+kx3,v+kv3);
t = t + dt;
x = x + (1.0/6.0)*(kx1 + 2*kx2 + 2*kx3 + kx4);
v = v + (1.0/6.0)*(kx1 + 2*kv2 + 2*kv3 + kv4);
// output for the step? Depending on the time?
}

In C++ finding sinx value with Taylor's Series

I am trying to write a block of codes in C++ that calculates sinX value with Taylor's series.
#include <iostream>
using namespace std;
// exp example
#include <cstdio> // printf
#include <cmath> // exp
double toRadians(double angdeg) //convert to radians to degree
{ //x is in radians
const double PI = 3.14159265358979323846;
return angdeg / 180.0 * PI;
}
double fact(double x) //factorial function
{ //Simply calculates factorial for denominator
if(x==0 || x==1)
return 1;
else
x * fact(x - 1);
}
double mySin(double x) //mySin function
{
double sum = 0.0;
for(int i = 0; i < 9; i++)
{
double top = pow(-1, i) * pow(x, 2 * i + 1); //calculation for nominator
double bottom = fact(2 * i + 1); //calculation for denominator
sum = sum + top / bottom; //1 - x^2/2! + x^4/4! - x^6/6!
}
return sum;
}
int main()
{
double param = 45, result;
result = mySin(toRadians(param)); //This is my sin value
cout << "Here is my homemade sin : " << result << endl;
result = sin(param); //This is library value
cout << "Here is the API sin : " << result << endl;
return 0;
}
So my program works without any error. My output is exactly:
Here is my homemade sin : nan
Here is the API sin:0.850904
I know I am making a big logic mistake but I couldn't find it out. It is my second week with C++. I am more familiar with Java. I coded the same thing and It worked absolutely perfect. The answers matched each other.
Thanks for your time and attention!
in fact, you miss the return: x*fact(x-1); should be return x*fact(x-1);. You can see the compiler complaining if you turn the warnings on. For example, with GCC, calling g++ -Wall program.cpp gives Warning: control reaches end of non-void function for the factorial function.
The API sin also needs the angle in radians, so change result=sin(param); into result=sin(toRadians(param));. Generally, if in doubt about the API, consult the docs, like here.
Your codes seems to have some logical mistakes. Here is my corrected one:
#include <iostream>
using namespace std;
double radians(double degrees) // converts degrees to radians
{
double radians;
double const pi = 3.14159265358979323846;
radians = (pi/180)*degrees;
return radians;
}
double factorial(int x) //calculates the factorial
{
double fact = 1;
for(; x >= 1 ; x--)
{
fact = x * fact;
}
return fact;
}
double power(double x,double n) //calculates the power of x
{
double output = 1;
while(n>0)
{
output =( x*output);
n--;
}
return output;
}
float sin(double radians) //value of sine by Taylors series
{
double a,b,c;
float result = 0;
for(int y=0 ; y!=9 ; y++)
{
a= power(-1,y);
b= power(radians,(2*y)+1);
c= factorial((2*y)+1);
result = result+ (a*b)/c;
}
return result;
}
double n,output;
int main()
{
cout<<"enter the value\t";
cin>>n;
n = radians(n);
cout<< "\nthe value in radians is\t"<< n << "\n";
output = sin(n);
cout<< "\nsine of the given value is\t"<< output;
return 0;
}
The intention of this program was to use custom functions instead of libraries to make learning for others easy.
There are four user defined functions in this program.The first three user defined functions 'radians()', 'factorial()','power()', are apparently simple functions that perform operations as their name suggests.
The fourth function 'sin()' takes input in radians given by the function 'radians()'. The sin function uses Taylors series iterated term wise in the function's 'for(int y= 0;y!=9;y++)' loop till nine iterations to calculate the output.The 'for()' loop iterates the general mathematical expression: Term(n)=((-1)^n).(x^(2n+1))/(2n+1)!
sin(x)= x- x^3/3! + x^5/5! -x^7/7! + x^9/9!
=x-x^3/2*3 (1- x^2/4*5 + x^4/4*5*6*7 + x^6/4*5*6*7*8*9)
=x - x^3/2*3 {1- x^2/4*5(1- x^2/6*7 + x^4/6*7*8*9)}
=x - x^3/2*3 [{1- x^2/4*5 ( 1- x^2/6*7 (1- x^2/8*9))}]
=x(1 - x^2/2*3 [{1- x^2/4*5 ( 1- x^2/6*7 (1- x^2/8*9))}])
double sin_series_recursion(double x, int n){
static double r=1;
if(n>1){
r=1-((x*x*r)/(n*(n-1)));
return sin_series_recursion(x,n-2);
}else return r*x;
}

Infinite loop calculating cubic root

I'm trying to make a function that calculates the cubic root through Newton's method but I seem to have an infinite loop here for some reason?
#include <iostream>
#include <math.h>
using namespace std;
double CubicRoot(double x, double e);
int main()
{
cout << CubicRoot(5,0.00001);
}
double CubicRoot(double x, double e)
{
double y = x;
double Ynew;
do
{
Ynew = y-((y*y)-(x/y))/((2*y)+(x/(y*y)));
cout << Ynew;
} while (abs(Ynew-y)/y>=e);
return Ynew;
}
You have not updated your y variable while iteration.
Also using abs is quite dangerous as it could round to integer on some compilers.
EDIT
To clarify what I've mean: using abs with <math.h> could cause implicit type conversion problems with different compiles (see comment below). And truly c++ style would be using the <cmath> header as suggested in comments (thanks for that response).
The minimum changes to your code will be:
double CubicRoot(double x, double e)
{
double y = x;
double Ynew = x;
do
{
y = Ynew;
Ynew = y-((y*y)-(x/y))/((2*y)+(x/(y*y)));
cout << Ynew;
} while (fabs(Ynew-y)/y>=e);
return Ynew;
}
You can change
Ynew = y-((y*y)-(x/y))/((2*y)+(x/(y*y)));
to the equivalent, but more recognizable expression
Ynew = y*(y*y*y+2*x)/(2*y*y*y+x)
which is the Halley method for f(y)=y^3-x and has third order convergence.

Error in job Build for constructing C++ program to determine range

I was till was experiencing some issues until i made the change to my formula for gravity. all is working now. thanks everyone. I appreciate all the great feedback
#include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
// Initialize objects:
double angle = 0.0;
double velocity = 0.0;
double range = 0.0;
const double PI = 3.141592653589793238;
const double gravity = 9.8; //meters pers second
// Input:
cout << "takeoff angle: ";
cin >> angle;
cout << "Please enter velocity: ";
cin >> velocity;
// Process
angle = angle * PI / 180;
range = sin(2 * angle) * velocity * velocity / gravity;
cout << " range " << range << endl;
system("pause");
return 0;
}
range = sin(* angle)*velocity pow(2);
This is not valid C++.
pow is a function that takes two arguments. x^y would be represented as pow(x, y).
Also, sin(*angle) is invalid as angle is neither a pointer nor a class with a defined * operator.
I think this is what you're looking for:
range = sin(2 * angle) * velocity * velocity / gravity;
// (No need to use pow(velocity, 2) over velocity * velocity)
(This is the correct formula for range)
You defined angle as a double, so you don't want to dereference it by writing *angle.
pow() takes two arguments, so you probably want to write pow(velocity,2).
sin(angle)*pow(velocity,2) should work. I'd recommend sin(angle)*velocity*velocity, as you don't need to use pow(x,2) if you only want to calculate x*x.
Oh, and note that gravity is 0.0 in your code, as it is defined as velocity*9.8 while velocity is 0.0.

Squareroot returning not a number in C++

In the program below, I am trying to calculate the distance between two points. For this, I have made two Point objects. In the method that returns the distance, I have used the distance formula to calculate distance between two points in space. However, every time I run the program, I get a not a number value, which shouldn't be there. Please help.
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
class Point
{
public:
Point(int a, int b);
~Point();
double getDistance(Point& P2);
void setPoints(int a, int b);
int getX();
int getY();
private:
int x;
int y;
};
Point::Point(int a, int b)
{
setPoints(a,b);
}
Point::~Point()
{
//Nothing much to do
}
void Point::setPoints(int a, int b)
{
x = a;
y = b;
}
double Point::getDistance(Point& P2)
{
int xdiff = P2.getX()-this->getX();
int ydiff = P2.getY()-this->getY();
xdiff = xdiff*xdiff;
ydiff = ydiff*ydiff;
double retval = sqrt((xdiff) - (ydiff));
return retval;
}
int Point::getX()
{
return x;
}
int Point::getY()
{
return y;
}
int main(int argc, char* argv[])
{
Point P1(0,0);
Point P2(0,1);
Point& pr = P2;
cout<<P1.getDistance(pr)<<endl;
return 0;
}
Your formula is wrong. It's not
sqrt(xdiff - ydiff)
but
sqrt(xdiff + ydiff)
You're trying to get the sqrt(-1) which is indeed not a number (or not a real number).
Here's how to figure this sort of thing out for yourself, or at least get a lot closer to a good StackOverflow question:
You know the problem is in the sqrt() call. So, what is it being called with? In this case, you could trace through the computation manually:
int xdiff = P2.getX()-this->getX(); // this is 0 - 0, which is 0.
int ydiff = P2.getY()-this->getY(); // this is 1 - 0, which is 1.
xdiff = xdiff*xdiff; // this is still 0.
ydiff = ydiff*ydiff; // this is still 1.
double retval = sqrt((xdiff) - (ydiff)); // this is sqrt(0 - 1), or sqrt(-1).
Alternately, in more complicated cases -- and to check your work, you could either use a debugger to print out the values of the arguments, or you could insert print statements:
xdiff = xdiff*xdiff;
ydiff = ydiff*ydiff;
cout << 'xdiff: ' << xdiff << ' ydiff: ' << ydiff << endl
cout << 'computing sqrt(' << xdiff - ydiff << ')' << endl
double retval = sqrt((xdiff) - (ydiff));
Either way, you now know that you're computing sqrt(-1), and you can try running that directly to confirm that it does indeed produce the same result. So either you have a question of "Why is sqrt(-1) returning NaN?" or a question of "Why is my distance calculation trying to compute the square root of a negative number?"
Hopefully you already know the answer to the first question, and the second question should indicate that you need to double-check your distance formula, which should have showed you the answer pretty quickly -- but even if you can't figure out why it's doing that, it at least makes a more useful question to ask here.
You should be adding here, not subtracting:
double retval = sqrt((xdiff) - (ydiff)); // correct is +
Subtracting causes you to take the square root of -1 due to the input data, which is not a (real) number.
As craigmj said, the formula for distance is sqrt ((x1-x2) + (y1-y2)). It's addition not subtraction. What your doing is generating an imaginary number (sqrt (-1)) which will cause an error.
Just a tip of advice, but do not create the destructor if it doesn't do anything; a destructor will be provided for you. Adding a destructor that doesn't do anything just adds unneeded code and makes it look messier.
Also in the getDistance function, you do not need to use this ->getX() and this-> getY(). Since this is a member function it has access to private data, therefore you can directly access the variables through x and y.