Solving equation for y - c++

When testing out the equation I get a -1.#IND00 as an answer when it solves for y. I'm basically trying to create a program that solves for y give the equation below
y=y/(3/17)-z+x/(a%2)+PI
#include <stdio.h>
#include <math.h>
#define PI 3.14
int main (void)
{
int a=0;
double z=0,x=0,y=0;
printf("Values for x, z, and a:");
scanf("%lf%lf%d", &x,&z,&a);
y = (((y/(double)(3/17)))-z + (x/(a%2))+PI);
printf("y = %lf\n", y);
return 0;
}

Since there are no questionmarks, I assume the question is "How do you write a C++ program that solves this equation?"
C++ is a programming language and by itself is not able to solve your equation, i.e. C++ won't do any transformation to your equation to get it into a form where y occurs only on the lefthand side and all parameters on the righthand side. You have to transform it yourself, manually or by using a solver.
What happens in the posted code?
Lets start at the leftmost part of the equation y/(double)(3/17) from inside out according to the parentheses:
3/17 is interpreted as integer division, which results in 0;
(double)(0) casts the integer 0 into a double of 0.0;
y/0.0 is a division by 0 as explained in this post which results in your error.
You could fix this as pointed out in the comments by either casting the first integer like (double)3/17 or turning the integer 3 into a double 3.0 or using static_cast.
However, y is still initialized to 0, so y/(double)3/17 is 0 and the equation calculated is basically -z + x/(a%2) + PI.
So, unless you transform the equation and put the transformed equation into the code, you won't get the results you expect.

Related

How do I input a quadratic equation in C++?

We were given an assignment to program the following, which I have been trying to figure out how to solve for the last 2 hours but to no avail.
How do you actually solve a complex formula having different operations in one mathematical expression?
For you to properly understand which of the operations are to be solved in order, try recreating the quadratic equation, ax^2 + bx + c, in C++ on your own!
Instructions:
The value of a, b, c, and x are already provided for you in the code editor. Remake the formula using C++'s math functions and operators and store it into one variable.
Print the value of the variable that stores the formula. To understand which to actually solve first in the equation, try tracing it out by yourself and manually solve it and see if your answer match that of the sample output.
Sample output: 16
TL;DR I am told to recreate the quadratic equation on my own using the given variables with their values.
Here is my current output which failed:
#include<iostream>
#include <cmath>
int main(void) {
int a = 2;
int b = 2;
int c = 4;
int x = 2;
// TODO:
// 1. Compute for the result of the quadratic equation
// using the variables provided above and the math library
double result;
result = (a * x + b * x) pow(2, 2) + c;
// 2. Print the output required by the output sample
std::cout << result;
return 0;
}
It prints out 4 when it should be 16.
You use this code:
result = a * pow(x, 2) + b * x + c;

Sizing down the value of 'g' for projectile motion

For my school project, my team is doing a paper toss game. You get the input for angle and velocity manually from the user. For calculating the X & Y co-ordinates of the projectile I use the formula
y= x * tan(a) - (g * X * X/2 * U * cos(a))
When is run this , after a certain point of time i start getting absurd values, such as -500 or -1000 for Y. Sometimes it reaches -60000. I suspect that this is because of 'g'. Please help me out with this problem.
I forgot to say that i am running a loop , for x=0 to some value (co-ordinate which corresponds to range , specifically). Also we are supposed to code using MD-DOS IDE'S(like turbo c++; our textbooks are old) and i code using Turbo c++.
I have tried setting different values for 'g' like 0.01 and 1, but nothing seems to work.
#include <iostream.h>
#include <conio.h>
#include <math.h>
{clrscr();
void projectile(int u , int a) //function which calculates values of X&Y
{int vcos=cos(a),vtan=tan(a),x,y,int g=10;
for(x=0;x<200;x++)
{ int p=((g*x*x)/(2*u*vcos*vcos));
y=(x*vtan)-p;
cout<<x<<","<<y; //cout statement to check the co-ordinates.
}
}
As values of X increase, I get really crazy outputs for Y like -32500 or -17000. I really suspect this due to the value of 'g' being used. Else it is a problem in calculating the angle value for each and every stage in the projectile. If anything else, please point out. Also please answer with functions or header files that are used in MD-DOS IDE'S (turbo c++ to be specific)
The main error seems to be using int variables for floating point quantities.
int vcos=cos(a),vtan=tan(a);
int p = ...;
In the calculation these are clearly continuously varying quantities which should be represented in a C++ program by a double.
double vcos=cos(a),vtan=tan(a);
double g = 0.01;
double p = ...;
etc.

Calculations failed because of - nan

My exercise is to write code which will print the value of this phrase
I have written a code which should work, but when I try to print a value I receive "the value is -nan".
//My Code
#include <iostream>
#include <stdio.h>
#include <cmath>
using namespace std;
int main()
{
double y;
double x = 21;
y = 30 * sqrt(x * (1/(tan(sqrt(3*x) - 2.1))));
printf ("The value is: \n=> %f", y );
}
My question is how can I print the proper value?
try this
printf( "sqrt(3*x) = %lf\n", sqrt(3*x));
printf( "sqrt(3*x) - 2.1 = %lf\n", sqrt(3*x) - 2.1);
printf( "tan(sqrt(3*x) - 2.1) = %lf\n", tan(sqrt(3*x) - 2.1));
then you will notice that the last one is negative which will result in a sqrt of a negative number, thus the NaN
The problem is that, depending on the unit (radians or degrees), you get different results with trigonometric functions. Keep in mind that the tan function expects its argument in radians.
sqrt(3*21)-2.1 = 5.837, and you have to calculate its tangent. It is indeed negative if we work with radians (it is around -0.478), leading to the square root of a negative number which is NaN (Not a Number), but if you use degrees then it is +0.102 and you can complete the calculation. If you want to have the result you would have with degrees, considering the function accepts radians, you must convert the number. The conversion is simple: multiply by Pi and divide by 180. Like this:
y = 30 * sqrt(x * (1/(tan((sqrt(3*x) - 2.1)*M_PI/180))));
In this case the result is 429.967.
If the problem is not related with conversion to radians, i.e. multiplication by M_PI / 180.
In general, operations that produce NaN (Not a Number)1 are:
In your case the result of tan() is negative which leads to negative input value for the outer sqrt(), which is the last example from the above table.
To resolve the problematic situation you could either use some mathematical trick2 and try to rewrite the expression such that it doesn't produce a NaN, or if the problem is in the negative square root, you can use the #include <complex> and:
std::complex<double> two_i = std::sqrt(std::complex<double>(-4));
The rest of the answers provide you with a strategy of how to identify the NaN source, by checking each computation involved
1. Bit patterns reserved for special quantities to handle exceptional situations like taking the square root of a negative number, other than aborting computation are called NaNs.
2. Use trigonometric relations.
where #define M_PI = 3.14159265358979323846;

Evenly distribute grid cells horizontally/vertically?

I'm trying to draw a grid inside a window of game_width=640 and game_height=480. The numbers of grid cells is predefined. I want to evenly distribute the cells horizontally and vertically.
void GamePaint(HDC dc)
{
int numcells = 11;
for(int i = 1; i <= numcells; i++)
{
int y = <INSERT EQUATION>;
MoveToEx(dc, 0, y, NULL);
LineTo(dc, game_width, y);
}
// solving the horizontal equation will in turn solve the vertical one so no need to show the vertical code
}
The first equation came to mind was:
i * (game_height / numcells)
The notion behind this is to divide the total height by the number of cells to get the even cell size, which is then multiplied by i in each iteration of the loop to get the correct y coordinate of the beginning of the horizontal line.
The problem with that is that it seems to leave an extra small cell at the end:
I figured this must have something to do with that integral division, so we come to the second equation:
(int)(i * ((float)game_height / numcells))
The idea is to avoid the integer division, do a float division, multiply by i like before and cast the result back to int. This works well, no extra small cell at the end!
What's driving me nuts, is this equation:
i * game_height / numcells
which seems to have the same effect as the previous equation, but of course with the added benefit of not doing any casting. I can't figure out why this doesn't suffer from the integer division issues in the first equation.
Note that mathematically: X * (Y / Z) == X * Y / Z
So there's definitely a problem with integer division in the first equation.
Here's a video watching these 3 equations in the debugger watch window.
You can see an increasing gap between the result of the first equation vs the second and third (which always had the same result) as i increases.
Why is the 3rd equation giving correct results as the second equation and not suffering from the integral division error in the first equation? I just can't seem to wrap my head around it...
Any help is appreciated.
The answer is in the order of operations performed. The first equation
int y = i * (game_height / numcells);
performs the division first, and magnifies the rounding error by multiplying with i. The further you move down/to the right, the larger the accumulated rounding error becomes.
The last equation
int y = i * game_height / numcells;
is evaluated left to right. The relative error gets smaller, as you are dividing larger numbers (i * game_height). You still have a rounding error, but it doesn't accumulate. The fact, that you do not wind up with extra space at the final evaluation is, that i is equal to numcells, essentially cancelling each other out. You will always see y == game_height in the final iteration.
Using floating point operations is still more accurate: While the rounding error using integer math is in the interval [0 .. numcells) for each line, floating point math reduces that to [0 .. 1). You will see more evenly distributed lines using floating point math.
Note: On Windows you can use MulDiv instead of the integer equation, to prevent common errors such as transient overflows.

lagrange approximation -c++

I updated the code.
What i am trying to do is to hold every lagrange's coefficient values in pointer d.(for example for L1(x) d[0] would be "x-x2/x1-x2" ,d1 would be (x-x2/x1-x2)*(x-x3/x1-x3) etc.
My problem is
1) how to initialize d ( i did d[0]=(z-x[i])/(x[k]-x[i]) but i think it's not right the "d[0]"
2) how to initialize L_coeff. ( i am using L_coeff=new double[0] but am not sure if it's right.
The exercise is:
Find Lagrange's polynomial approximation for y(x)=cos(π x), x ∈−1,1 using 5 points
(x = -1, -0.5, 0, 0.5, and 1).
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
using namespace std;
const double pi=3.14159265358979323846264338327950288;
// my function
double f(double x){
return (cos(pi*x));
}
//function to compute lagrange polynomial
double lagrange_polynomial(int N,double *x){
//N = degree of polynomial
double z,y;
double *L_coeff=new double [0];//L_coefficients of every Lagrange L_coefficient
double *d;//hold the polynomials values for every Lagrange coefficient
int k,i;
//computations for finding lagrange polynomial
//double sum=0;
for (k=0;k<N+1;k++){
for ( i=0;i<N+1;i++){
if (i==0) continue;
d[0]=(z-x[i])/(x[k]-x[i]);//initialization
if (i==k) L_coeff[k]=1.0;
else if (i!=k){
L_coeff[k]*=d[i];
}
}
cout <<"\nL("<<k<<") = "<<d[i]<<"\t\t\tf(x)= "<<f(x[k])<<endl;
}
}
int main()
{
double deg,result;
double *x;
cout <<"Give the degree of the polynomial :"<<endl;
cin >>deg;
for (int i=0;i<deg+1;i++){
cout <<"\nGive the points of interpolation : "<<endl;
cin >> x[i];
}
cout <<"\nThe Lagrange L_coefficients are: "<<endl;
result=lagrange_polynomial(deg,x);
return 0;
}
Here is an example of lagrange polynomial
As this seems to be homework, I am not going to give you an exhaustive answer, but rather try to send you on the right track.
How do you represent polynomials in a computer software? The intuitive version you want to archive as a symbolic expression like 3x^3+5x^2-4 is very unpractical for further computations.
The polynomial is defined fully by saving (and outputting) it's coefficients.
What you are doing above is hoping that C++ does some algebraic manipulations for you and simplify your product with a symbolic variable. This is nothing C++ can do without quite a lot of effort.
You have two options:
Either use a proper computer algebra system that can do symbolic manipulations (Maple or Mathematica are some examples)
If you are bound to C++ you have to think a bit more how the single coefficients of the polynomial can be computed. You programs output can only be a list of numbers (which you could, of course, format as a nice looking string according to a symbolic expression).
Hope this gives you some ideas how to start.
Edit 1
You still have an undefined expression in your code, as you never set any value to y. This leaves prod*=(y-x[i])/(x[k]-x[i]) as an expression that will not return meaningful data. C++ can only work with numbers, and y is no number for you right now, but you think of it as symbol.
You could evaluate the lagrange approximation at, say the value 1, if you would set y=1 in your code. This would give you the (as far as I can see right now) correct function value, but no description of the function itself.
Maybe you should take a pen and a piece of paper first and try to write down the expression as precise Math. Try to get a real grip on what you want to compute. If you did that, maybe you come back here and tell us your thoughts. This should help you to understand what is going on in there.
And always remember: C++ needs numbers, not symbols. Whenever you have a symbol in an expression on your piece of paper that you do not know the value of you can either find a way how to compute the value out of the known values or you have to eliminate the need to compute using this symbol.
P.S.: It is not considered good style to post identical questions in multiple discussion boards at once...
Edit 2
Now you evaluate the function at point y=0.3. This is the way to go if you want to evaluate the polynomial. However, as you stated, you want all coefficients of the polynomial.
Again, I still feel you did not understand the math behind the problem. Maybe I will give you a small example. I am going to use the notation as it is used in the wikipedia article.
Suppose we had k=2 and x=-1, 1. Furthermore, let my just name your cos-Function f, for simplicity. (The notation will get rather ugly without latex...) Then the lagrangian polynomial is defined as
f(x_0) * l_0(x) + f(x_1)*l_1(x)
where (by doing the simplifications again symbolically)
l_0(x)= (x - x_1)/(x_0 - x_1) = -1/2 * (x-1) = -1/2 *x + 1/2
l_1(x)= (x - x_0)/(x_1 - x_0) = 1/2 * (x+1) = 1/2 * x + 1/2
So, you lagrangian polynomial is
f(x_0) * (-1/2 *x + 1/2) + f(x_1) * 1/2 * x + 1/2
= 1/2 * (f(x_1) - f(x_0)) * x + 1/2 * (f(x_0) + f(x_1))
So, the coefficients you want to compute would be 1/2 * (f(x_1) - f(x_0)) and 1/2 * (f(x_0) + f(x_1)).
Your task is now to find an algorithm that does the simplification I did, but without using symbols. If you know how to compute the coefficients of the l_j, you are basically done, as you then just can add up those multiplied with the corresponding value of f.
So, even further broken down, you have to find a way to multiply the quotients in the l_j with each other on a component-by-component basis. Figure out how this is done and you are a nearly done.
Edit 3
Okay, lets get a little bit less vague.
We first want to compute the L_i(x). Those are just products of linear functions. As said before, we have to represent each polynomial as an array of coefficients. For good style, I will use std::vector instead of this array. Then, we could define the data structure holding the coefficients of L_1(x) like this:
std::vector L1 = std::vector(5);
// Lets assume our polynomial would then have the form
// L1[0] + L2[1]*x^1 + L2[2]*x^2 + L2[3]*x^3 + L2[4]*x^4
Now we want to fill this polynomial with values.
// First we have start with the polynomial 1 (which is of degree 0)
// Therefore set L1 accordingly:
L1[0] = 1;
L1[1] = 0; L1[2] = 0; L1[3] = 0; L1[4] = 0;
// Of course you could do this more elegant (using std::vectors constructor, for example)
for (int i = 0; i < N+1; ++i) {
if (i==0) continue; /// For i=0, there will be no polynomial multiplication
// Otherwise, we have to multiply L1 with the polynomial
// (x - x[i]) / (x[0] - x[i])
// First, note that (x[0] - x[i]) ist just a scalar; we will save it:
double c = (x[0] - x[i]);
// Now we multiply L_1 first with (x-x[1]). How does this multiplication change our
// coefficients? Easy enough: The coefficient of x^1 for example is just
// L1[0] - L1[1] * x[1]. Other coefficients are done similary. Futhermore, we have
// to divide by c, which leaves our coefficient as
// (L1[0] - L1[1] * x[1])/c. Let's apply this to the vector:
L1[4] = (L1[3] - L1[4] * x[1])/c;
L1[3] = (L1[2] - L1[3] * x[1])/c;
L1[2] = (L1[1] - L1[2] * x[1])/c;
L1[1] = (L1[0] - L1[1] * x[1])/c;
L1[0] = ( - L1[0] * x[1])/c;
// There we are, polynomial updated.
}
This, of course, has to be done for all L_i Afterwards, the L_i have to be added and multiplied with the function. That is for you to figure out. (Note that I made quite a lot of inefficient stuff up there, but I hope this helps you understanding the details better.)
Hopefully this gives you some idea how you could proceed.
The variable y is actually not a variable in your code but represents the variable P(y) of your lagrange approximation.
Thus, you have to understand the calculations prod*=(y-x[i])/(x[k]-x[i]) and sum+=prod*f not directly but symbolically.
You may get around this by defining your approximation by a series
c[0] * y^0 + c[1] * y^1 + ...
represented by an array c[] within the code. Then you can e.g. implement multiplication
d = c * (y-x[i])/(x[k]-x[i])
coefficient-wise like
d[i] = -c[i]*x[i]/(x[k]-x[i]) + c[i-1]/(x[k]-x[i])
The same way you have to implement addition and assignments on a component basis.
The result will then always be the coefficients of your series representation in the variable y.
Just a few comments in addition to the existing responses.
The exercise is: Find Lagrange's polynomial approximation for y(x)=cos(π x), x ∈ [-1,1] using 5 points (x = -1, -0.5, 0, 0.5, and 1).
The first thing that your main() does is to ask for the degree of the polynomial. You should not be doing that. The degree of the polynomial is fully specified by the number of control points. In this case you should be constructing the unique fourth-order Lagrange polynomial that passes through the five points (xi, cos(π xi)), where the xi values are those five specified points.
const double pi=3.1415;
This value is not good for a float, let alone a double. You should be using something like const double pi=3.14159265358979323846264338327950288;
Or better yet, don't use pi at all. You should know exactly what the y values are that correspond to the given x values. What are cos(-π), cos(-π/2), cos(0), cos(π/2), and cos(π)?