Reputation:
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?
Upvotes: 0
Views: 104
Reputation: 36082
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
Upvotes: 3
Reputation: 6467
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 NaN
s.
2. Use trigonometric relations.
where #define M_PI = 3.14159265358979323846;
Upvotes: 0
Reputation: 5716
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
.
Upvotes: 2