c++ Receiving "-1.#IND" from output? - c++

Pretty simple problem here:
When I test the wrong data input I give an error message but -1.#IND comes up after it?
for instance I type a negative where there should be a positive and I get "wrong input dummy-1.#IND"
#include "Header.h"
void error_rep(){
cout<<"Wrong input dummy";
}
double ctok(double c){
double j = c *273.15;
if (j >= -273.15){
return j;
}
else
error_rep();
}
int main(){
double c = 0;
cin >> c;
double k = ctok(c);
cout<<k<<endl;
keep_window_open();
}
What does this mean? and why is it coming up? How do I get rid of it?

What does this mean?
It's Microsoftese for "not a number". It means that k is not a valid floating-point number.
and why is it coming up?
When your range test fails, you don't return a value. This gives undefined behaviour; in practice, it's likely to be equivalent to returning an uninitalised value, which is likely to be garbage. Your compiler should warn you about this, if you have suitable warnings enabled.
How do i get rid of it?
I'd report the error by throwing an exception; then nothing can attempt to use the invalid return value if the function fails. Alternatively, you could return a type with a testable "invalid" state, such as boost::optional<double> or std::pair<double, bool>, and test it before use.
By the way, if that's supposed to be converting degrees Celsius to Kelvin, then you want to add 273.15, not multiply by it; and compare with zero after the conversion (or with 273.15 before converting, if you prefer).

A good compiler with all warning turns on, will have say that an execution path doesn't have a return ...,
double ctok(double c){
double j = c *273.15;
if (j >= -273.15){
return j;
}
else {
error_rep();
///here
throw ;//somthing
}
}
and try-catch exception around ctok call

-1.#IND means that the double value is "negative indefinate NaN". Basically the value stored can't be represented as a number in a double.
See http://blogs.msdn.com/b/oldnewthing/archive/2013/02/21/10395734.aspx

Related

C++ Reversing Number using to_string, reverse, stoi combo giving runtime error Instance Out of Range

Stuck trying to resolve a runtime error due to an instance out of range exception. I'm taking the int into a string, reversing the string and returning it to int using stoi. Simple test numbers reverse perfectly but bigger numbers are out of range. Not sure where in the code to adjust for the out of range exception. Super stuck, please help.
int reverse(int x) {
bool negFlag = false;
if(x < 0)
{
negFlag = true;
}
string xString = std::to_string(abs(x));
std::reverse(xString.begin(), xString.end());
int xNum = std::stoi(xString);
return (negFlag == true)? -xNum: xNum;
}
Here is the error returned:
terminate called after throwing an instance of 'std::out_of_range'
what(): stoi
Last executed input: 1534236469
The smaller number work well.
Your input: 123
Output: 321
Expected: 321
Is there a \0 at the end of my string that is throwing everything off in the conversion? New to these C++ methods. Thanks so much. Would really love to nail these methods down and be able to use them with ease.
Vital Info:
Note: Assume we are dealing with an environment which could only store
integers within the 32-bit signed integer range:
[-231 to +231 -1]
For the purpose of this problem, assume that your function returns 0 when
the reversed integer overflows.
-->> Not sure how to formulate an if statement that will return 0; when the 32-bit is exceeded.
The reverse of 1,534,236,469 is 9,646,324,351. The maximum value that a typical 32bit int can hold is 2,147,483,647, so it doesn't fit into it.
You need to have your function return something larger, e.g. long long (which is at least 64bit) and use the appropriate conversion function for it, e.g.:
long long reverse(int x) {
//...
long long xNum = std::stoll(xString);
//...
}
Whether you want to change the input type to something larger as well, depends on the maximum input value that your function is supposed to be able to process.
After your edit:
You can catch the conversion error and return 0 in that case (requires #include<stdexcept>):
try {
int xNum = std::stoi(xString);
// Maybe insert additional range test according to assignment (?)
return (negFlag == true)? -xNum: xNum;
} catch(const std::out_of_range&) {
return 0;
}
Assuming int to be 32bit two's-complement (which I understand the assignment is trying to suggest with the value range, which is presumable supposed to be [-2**31, 2**31-1]):
Also note that your initial call to abs has undefined behavior if x == -2**31, because 2**31 is not representable in the 32bit int. So you need to first make a special case for that before you call abs to avoid undefined behavior.
Similarly you need to consider the case where the result of the function should be -2**31. But you may notice that this case is irrelevant because its corresponding input value would already fall out-of-range of int.
The input range is bigger than an int can hold. Change it to long long and it should work.
long long reverse(long long x) {
bool negFlag = false;
if(x < 0)
{
negFlag = true;
}
string xString = std::to_string(abs(x));
std::reverse(xString.begin(), xString.end());
long long xNum = std::stoll(xString);
return (negFlag == true)? -xNum: xNum;
}
Note that the return type needs to be changed as well.

Problems finding a number's square root with bisection method

#include<iostream>
#include<cmath>
using namespace std;
double bisection(double errorVal, double userNum){
double upper=userNum, lower=0;
double mid=(lower+upper)/2.0;;
while(mid*mid!=userNum){
double mid=(lower+upper)/2.0;
if(mid*mid>userNum){
upper=mid;
} else {
lower=mid;
}
}
return mid;
}
int main(){
double errorVal=0, userNum=0;
std::cout<<"Please enter a number (larger than 0) to calculate its square root, and the desired margin of error."<<std::endl;
std::cin>>userNum>>errorVal;
bisection(errorVal,userNum);
std::cout<<"The calculated result is "<<bisection(errorVal,userNum)<<". The error is "<<abs(bisection(errorVal,userNum)-sqrt(userNum))<<"."<<std::endl;
}
This is a program I have written to find the square root of any number inputted via the bisection method. I must be doing something wrong here because I am not getting any output once I enter the two input parameters, the process just gets stuck there.
I would also like to know how to properly implement errorVal, as to specify the margin of error allowed. Thanks.
The error value is used to fix any rounding inaccuracies which occur while doing floating point operations.
The following statement would seldom be true, therefor your loop is likely to continue for a long time.
while(mid*mid==userNum)
The usual way to compare two floating points after calculation is
fabs(x1-x2) < e //where, fabs retrieves the absolute value,
//x1,2 are the numbers to compare
//and e is the epsilon chosen.
So, fixing the error value, or commonly referred to as epsilon, would fix the loop as well.
double bisection(double errorVal, double userNum){
double upper=userNum, lower=0;
double mid=(lower+upper)/2.0;
//error val added
//** fabs(mid*mid - userNum) < errorVal is true if the numers are "equal"
//** and you want to run the loop as long as the are NOT "equal"
while(!(fabs(mid*mid - userNum) < errorVal)){
mid=(lower+upper)/2.0;
if(mid*mid>userNum){
upper=mid;
} else {
lower=mid;
}
}
return mid;
}
See:
http://www.cplusplus.com/reference/cmath/fabs/
https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/

C++ return a string or an int depending on input

I know a function can only return one type of value, but I'm not sure how else to phrase this.
My function finds a factorial, and I want to print an error message if the input is less than 0.
int fact(int a){
if (a>=0){
//calculate factorial
}
return(product);
}
else {
cout << "Factorials of negative numbers are not defined\n";
return(0);
}
}
This works, but I only want the error message to be displayed if a is less than 0. Right now, my output for negatives is
Take the factorial of: -2
Factorials of negative numbers are not defined
0
I know it's a minor complaint, but is there any way to get rid of the 0? Returning NULL still prints the 0. Removing return(0) from the else statement prints 4757824.
"Separation of concerns" your fact() method is both calculating the factorial and printing an error. It really shouldn't do both!
Why not have fact() return some known but not legal value (say -1) when an error occurs. The calling code can then check whether fact() worked or not.
Don't forget you will have another error condition if the input is too big...

Comparing double error C++

recently I bump into a problem while comparing a double in an if statement. I was trying to cout the number of whole numbers in a double. Being a beginner, I am not sure what gone wrong in my code.
This is my code:
#include <iostream>
using namespace std;
int main(){
int x=0;//convert double to int
long double Out;//Result
long double In=10;//Input double
//Loop Begin
while(In>0){
x=In;//convert double to int
Out= (x/In);//Out(test if whole number, will return 1)
//test for 1
////////////////
if(Out == 1 ){
cout<<"[Whole Number] ";
}
////////////////
//test end
cout<<"In :"<<In<<", ";
cout<<"X :"<<x<<", ";
cout<<"Out :"<<Out<<endl;
In-=0.1;//decrease to finish loop (eventually)
}
//Loop End
cin.get();
return 0;
}
This program will test and output the whole numbers in the double (In). I realized that the accuracy of the double was affecting the if statement which is why I can't get the "[Whole Number]" result. Although I found out that if I used (0.9999) in "if(Out >= 0.9999)" the comparison would work. But I am not sure of a solution, please help! Much appreciated!
Your while loop never stops , its a infinite loop . You are not doing anything with the value of "In" in the while loop hence it will always be greater than 0 ,therefore a infinite loop .
You should probably approach the problem more directly with modf:
double int_part, frac_part;
frac_part = std::modf(in, &int_part);
if (frac_part == 0) {
// int_part contains integer value.
} else {
// process the double non-integer floating point value.
}
Your code works perfectly fine. If you subtract 0.1 from 10.0, then chances are that the result is not an integer due to rounding errors, and your code tells you exactly that. The code isn't wrong, your expectations are wrong.
if (Out >= 0.9999)
is obviously not a solution, because it will always be true if In >= 10000.0.
Do to the way floating point numbers are converted to binary representation by the computer they are inherently inaccurate and thus make logical comparisons somewhat challenging (http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems). When performing such comparisons to floating point numbers you typically will do so utilizing an epsilon constant (http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm) that represents the maximum acceptable error in the comparison. In your case you need to select a suitable value for epsilon (say .000001). Then change your comparison to:
if(abs(out - 1) < epsilon){ //Take the difference between out and 1
cout<<"[Whole Number]"; //If it is "close enough" print to console
}
I am more of a Java guy but I believe you will need #include stdlib.h to utilize the abs() function.
Hope that helps!
Try using the modulus operator: http://www.cprogramming.com/tutorial/modulus.html
Something like if(In % 1 == 0) should work.

What is wrong with my exception handling here?

I am trying to write a custom function that can raise any number 'a' to the power 'b' and i'm only interested in getting the real portion of my answer. I have written my own function to handle, but it still fails when a is negative. Can any tell me how I go about fixing this, please?
#include <exception>
...
double power(double a, double b) {
double output;
try {output = pow(a,b);}
catch (std::domain_error) { //even if I use catch(...) I still get a NaN.
if (b==0.0) output = 1.0;
if (a==0.0) output = 0.0;
if (b<0.0) {
b=-1.0*b;
try {output = 1.0/pow(a,b);}
catch (std::domain_error){
a = -1.0*a;
output = -1.0/pow(a,b);
}}
else {
a=-1.0*a;
output = -1.0*pow(a,b);}
}
return output;
}
Many thanks for the replies. I have read the responses and made the following code.
double power(double a, double b) {
double output;
output = pow(a,b);
if (output != output) {
if (b==0.0) output = 1.0;
if (a==0.0) output = 0.0;
else if (b<0.0) {
b=-1.0*b;
output = 1.0/pow(a,b);
if (output != output) {
a = -1.0*a;
output = -1.0/pow(a,b);
}}
else {
a=-1.0*a;
output = -1.0*pow(a,b);}
}
if (output >= DBL_MAX) output = DBL_MAX;
if (output <= -DBL_MAX) output =-DBL_MAX;
if ((output >= -DBL_MIN) && (output <= DBL_MIN)) output = 0.0;
return output;
}
My only remaining question is how does c++ handle 1.0/inf? I hope that it will be caught by
if ((output >= -DBL_MIN) && (output <= DBL_MIN)) output = 0.0;
The floating point arithmetic handling doesn't throw std::exceptions: it just return special values that represent the exception:
In partucular, for the std::pow function, the documetation says:
...
Domain error occurs if base is 0 and exp is less than or equal to ​0​.
NAN is returned in that case
...
It doesn't say that std::domain_error is thrown, but that NAN is returned to represent thaat anomaly.
Since no throw is made, there is nothing to catch.
For your purposes, don't use exceptions: since you know what kind of input you want to handle, just pre-filter it.
Math functions do not throw exceptions - they set special exception flags (more about it in Floating-point environment, there is even example).
To check whether your pow function failed, either check whether the return value is NAN, or use one of the floating exception functions to do it (assuming you set it properly).