Squareroot returning not a number in C++ - 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.

Related

i want to make a program to do some usermade functuions like addition and stuff [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
#include <iostream>
#include <math.h>
using namespace std ;
int add (float,float);
int Multiply (float,float);
int division (float,float);
int subtract (float,float);
int main ()
{
float x,y,z;
float sum;
float multiply2;
float division2;
float subtract2;
cout<<"please enter the 3 FLOAT numbers you would like to do the processes on"<<endl;
cin>>x>>y>>z;
sum = addd(x, y,z);
cout << "Sum = " << sum;
return 0;
multiply2 = Multiplyy(x, y,z);
cout << "multiply = " << multiply2;
return 0;
division2 = divisionn(x, y,z);
cout << "division = " << division2;
return 0;
subtract2 = subtractt(x, y,z);
cout << "subtract = "<<subtract2 << sum;
return 0;
}
int addd(float a, float b,float c)
{
float addd;
addd = a + b + c;
return addd;
}
int Multiplyy(float a, float b,float c)
{
float Multiplyy;
Multiplyy = a * b * c;
return Multiplyy;
}
int divisionn(float a, float b,float c)
{
float divisionn;
divisionn = a / b / c;
return divisionn;
}
int subtractt(float a, float b,float c)
{
float subtractt;
subtractt = a - b -c;
return subtractt;
}
it's not working! it gives me error that identifier is not defined!
so yeah i tried everything i could do, it's very late and i really don't know what i am missing to be honest!
anyhelp would be very good
thanks!
Your forward declarations are incorrect. You have forward-declared your functions to accept two float arguments, but then your definitions take three arguments. In addition, the forward-declared function names are not correct (you forward-declare add, for example, but then you call and define addd later).
Fix your function forward declarations to take (float, float, float) instead of (float, float), and name them to match the rest of your program, and it will compile.
You have some other weirdness going on, such as declaring a variable named addd within the function addd (and in your other functions as well), which is confusing, but will not cause a compile-time error. This is what I would call a "style bug" -- the program will still run, but the source code is unnecessarily confusing. Declaring a new identifier that hides a previously-declared identifier is called "shadowing," and as a general rule it should be avoided because it creates confusion.
Your functions also truncate their results, because they accept float values but return int. Any fractional part of the computation will be discarded. (For example, addd(0.5, 1.5, 2.5) would be expected to return 4.5, but will instead return 4 because the float-to-int conversion discards the fractional 0.5 component.)

Durand-Kerner method to find roots of nonlinear equation

I am being asked to find the roots of f(x) = 5x(e^-mod(x))cos(x) + 1 . I have previously used the Durand-Kerner method to find the roots of the function x^4 -3x^3 + x^2 + x + 1 with the code shown below. I thought I could simply reuse the code to find the roots of f(x) but whenever I replace x^4 -3x^3 + x^2 + x + 1 with f(x) the program outputs nan for all the roots. What is wrong with my Durand-Kerner implementation and how do I go about modifying it to work for f(x)? I would be very grateful for any help.
#include <iostream>
#include <complex>
#include <math.h>
using namespace std;
typedef complex<double> dcmplx;
dcmplx f(dcmplx x)
{
// the function we are interested in
double a4 = 1;
double a3 = -3;
double a2 = 1;
double a1 = 1;
double a0 = 1;
return (a4 * pow(x,4) + a3 * pow(x,3) + a2 * pow(x,2) + a1 * x + a0);
}
int main()
{
dcmplx p(.9,2);
dcmplx q(.1, .5);
dcmplx r(.7,1);
dcmplx s(.3, .5);
dcmplx p0, q0, r0, s0;
int max_iterations = 100;
bool done = false;
int i=0;
while (i<max_iterations && done == false)
{
p0 = p;
q0 = q;
r0 = r;
s0 = s;
p = p0 - f(p0)/((p0-q)*(p0-r)*(p0-s));
q = q0 - f(q0)/((q0-p)*(q0-r)*(q0-s));
r = r0 - f(r0)/((r0-p)*(r0-q)*(r0-s0));
s = s0 - f(s0)/((s0-p)*(s0-q)*(s0-r));
// if convergence within small epsilon, declare done
if (abs(p-p0)<1e-5 && abs(q-q0)<1e-5 && abs(r-r0)<1e-5 && abs(s-s0)<1e-5)
done = true;
i++;
}
cout<<"roots are :\n";
cout << p << "\n";
cout << q << "\n";
cout << r << "\n";
cout << s << "\n";
cout << "number steps taken: "<< i << endl;
return 0;
}
The only thing I have been changing so far is the dcmplx f function. I have been changing it to
dcmplx f(dcmplx x)
{
// the function we are interested in
double a4 = 5;
double a0 = 1;
return (a4 * x * exp(-x) * cos(x) )+ a0;
}
The Durand-Kerner method that you're using requires the function to be continuous on the interval you are working.
Here we ahve a discrepancy between the mathematical view and the limits of the numeric applications. I'd propose you to plot your function (typing the formula in google will give you a quick overview of course for the real part). You'll notice that:
there are an infinity of roots due to the periodicity of the cosinus.
due to the x*exp(-x) the absolute value quickly rises up beyond the maximum precision that a floating point number can hold.
To understand the consequences on your code, I invite you to trace the different iteration. You'll notice that p, r and s are converging very quicky while q is diverging (apparently on the track of one of the huge peak):
At the 2nd iteration q is already at 1e74
At 3rd iteration already beyond what a double can store.
As q is used in the calculation of p,r and s, the error is propagated to the other terms
At 5th iteration, all terms are at NAN
It then continues bravely through the 100 iterations
Perhap's you could make it work by choosing different starting points. If not, you'll have to use some other method and carefully select the interwall on which you're working.
You should have noted in your documentation of the Durand-Kerner method (invented by Karl Weierstrass around 1850) that it only applies to polynomials. Your second function is far from being a polynomial.
Indeed, because of the mod function it has to be declared as a nasty function for numerical methods. Most of them rely on the continuity of the given function, i.e., if the value is close to zero, there is a good chance that there is a root nearby and if the sign changes on an interval then there is a root in the interval. Even the most basic derivate-free methods as the bisection method or Brents method on the sophisticated end of that class pre-suppose these properties.

Different IDE's different output?

I have the following problem : I write my code with the Qt IDE. I was informed that when people try to compile it with other IDE's (like codeblocks, or visual studio) The output they get is different and that there are maufunctions. Any ideas what can be causing this ? I will give you an example:
This is Newton's Method with a function who's root is 2.83something. I get the same, correct calulations each time I run it in Qt. I get "nan" in code blocks and something irrelevant as well in visual studio. I don't understand, do I have a mistake somewhere in my code ? What can be causing this ?
#include <iostream>
#include <cmath> // we need the abs() function for this program
using namespace std;
const double EPS = 1e-10; // the "small enough" constant. global variable, because it is good programming style
double newton_theorem(double x)
{
double old_x = x; // asign the value of the previous iteration
double f_x1 = old_x*old_x - 8; // create the top side of the f(x[n+1] equation
double f_x2 = 2 * old_x; // create the bottom side
double new_x = old_x - f_x1 / f_x2; // calculate f(x[n+1])
//cout << new_x << endl; // remove the // from this line to see the result after each iteration
if(abs(old_x - new_x) < EPS) // if the difference between the last and this iteration is insignificant, return the value as a correct answer;
{
return new_x;
}
else // if it isn't run the same function (with recursion YAY) with the latest iteration as a starting X;
{
newton_theorem(new_x);
}
}// newton_theorem
int main()
{
cout << "This program will find the root of the function f(x) = x * x - 8" << endl;
cout << "Please enter the value of X : ";
double x;
cin >> x;
double root = newton_theorem(x);
cout << "The approximate root of the function is: " << root << endl;
return 0;
}//main
Yes, you run into undefined behavior:
if(abs(old_x - new_x) < EPS) // if the difference between the last and this iteration is insignificant, return the value as a correct answer;
{
return new_x;
}
else // if it isn't run the same function (with recursion YAY) with the latest iteration as a starting X;
{
/*return*/ newton_theorem(new_x); // <<--- HERE!
}
Missing a return on the else branch.
We could try to explain why Qt works (its compiler automatically puts the result of newton_theorem in the return registry, or shares registries, or whatever), but the fact of the matter is anything can happen. Some compilers might behave the same on subsequent runs, some might crash all the time.

c++ convert a fractional part of a number into integer

I needed to convert a fractional part of a number into integer without a comma,
for example I have 3.35 I want to get just 35 part without zero or a comma,
Because I used the modf() function to extract the the fractional part but it gives me a 0.35
if there is any way to do that or to filter the '0.' part I will be very grateful if you show me how with the smaller code possible,
A bit more efficient than converting to a string and back again:
int fractional_part_as_int(double number, int number_of_decimal_places) {
double dummy;
double frac = modf(number,&dummy);
return round(frac*pow(10,number_of_decimal_places));
}
#include <iostream>
#include <cmath>
double round(double r) {
return (r > 0.0) ? std::floor(r + 0.5) : std::ceil(r - 0.5);
}
double floor_to_zero(double f) {
return (f > 0.0) ? std::floor(f) : std::ceil(f);
}
double sign(double s) {
return (s < 0.0) ? -1.0 : 1.0;
}
int frac(double f, int prec) {
return round((f - floor_to_zero(f)) * prec) * sign(f);
}
int main() {
double a = 1.2345;
double b = -34.567;
std::cout << frac(a, 100) << " " << frac(b, 100) << std::endl; // 23 57
}
another solution
int precision= 100;
double number = 3.35;
int f = floor(xx);
double temp = ( f - number ) * -1;
int fractional_part = temp * precision;
IF you need it as a string, a quite easy C style solution would be (should work for variable number of decimal places):
double yourNumber = 0.35f;
char buffer[32];
snprintf(buffer, 32, "%g", yourNumber);
strtok(buffer, "."); // Here we would get the part before . , should still check
char* fraction = strtok(NULL, ".");
int fractionAsInt = atoi(fraction);
This example lacks error handling in case of a bad string and is not feasible if you just need a fixed number of decimal places, since the arithmetic approaches work better there.
Something like this should work:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
static int get_frac(double value, unsigned short precision)
{
return (int)((value - (long)value) * pow(10, precision));
}
static int get_frac_no_trailing_zeros(double value, unsigned short precision)
{
int v = get_frac(value, precision);
while (v % 10 == 0)
v /= 10;
return v;
}
int main(int argc, char *argv[])
{
double v;
v = 123.4564;
printf("%.4f = %d\n", v, get_frac(v, 2));
printf("%.4f = %d\n", v, get_frac(v, 4));
printf("%.4f = %d\n", v, get_frac(v, 6));
printf("%.4f = %d\n", v, get_frac_no_trailing_zeros(v, 6));
return EXIT_SUCCESS;
}
You may also want to either avoid calling pow by having a user supply a number in a power of 10 in a first place, or use a lookup table.
Using some stl magic, here is the sample code:
typedef std::pair<int, int> SplitFloat;
SplitFloat Split(float value, int precision)
{
// Get integer part.
float left = std::floor(value);
// Get decimal part.
float right = (value - left) * float(std::pow(10, precision));
return SplitFloat(left, right);
}
It can be improved, but is pretty straightforward.
I just did something close to what you are trying to do, though I'm still pretty new. None the less, maybe this will help someone in the future as I landed here looking for results for my problem.
The first step is making sure that the variable that contains 3.35 is a double, but that's probably obvious.
Next, create a variable that is only an integer and set it's value equal to the value of the double. It will then only contain the whole number.
Then subtract the whole number (int) from the double. You will be left with the fraction/decimal value. From there, just multiply by 100.
Beyond the 100ths decimal value, you would have to do a little more configuring obviously, but it should be fairly simple to do with an if statement. If the decimal value is greater than .99, multiply 1000 instead etc..
Here's how I would do it.
#include <sstream>
#include <string>
int main()
{
double d = yourDesiredNumber; //this is your number
std::ostringstream out;
out << setprecision(yourDesiredPrecision) << std::fixed
<< std::showpoint << d;
std::istringstream in(out.str());
std::string wholePart; //you won't need this.
int fractionalPart;
std::getline(in, wholePart, '.');
in >> fractionalPart;
//now fractionalPart contains your desired value.
}
I'm pretty sure that instead of two different istringstream and ostringstream objects you could have gotten away with just one stringstream object, but I am not sure about the details (never used that class) so I didn't use it in the example.

C++ Use secant method to solve function

I have a school problem but I do not understand what it actually asks. Any of you have an idea what it's really asking for? I don't need code, I just need to understand it.
This is the problem:
Construct a computer program that uses the Secant method to solve the problem:
f(x)  =  (1+x) cos( sin(x)3 ) -  1.4   =  0
Starting with the initial guesses of x=2.0 and x=2.1, obtain an approximation to x such that  |f(x)| < 0.0000001.
This is my code from what I understand, but I think I'm not understanding the question correctly.
#include <iostream>
#include <cmath>
double secant(double x);
using namespace std;
int main()
{
double x = 2.0;
double r = 0.0;
int counter = 0;
while( r < 0 && counter <= 40)
{
r =secant(x);
cout << "x: " << x << ", f(x): " << r << endl;
counter++;
x += 0.1;
}
return 0;
}
double secant(double x)
{
double r;
r = (1+x) * cos(pow(sin(x), 3.0)) - 1.4;
return r;
}
You are supposed to use the Secant Method: http://en.wikipedia.org/wiki/Secant_method
Follow the method as described in the article. It is an iterative method much like Netwon's method. You'll need to make a function to evaluate x(n+1) given x(n) and iterate it until your margin of error is less than specified.
The coding side of this may prove fairly straightforward as long as you know what the secant method is. Also, that page has a code example. That should prove pretty useful. :)