Storing erroneous value in integer [duplicate] - c++

This question already has answers here:
Can an integer be NaN in C++?
(5 answers)
Closed 9 years ago.
I have a complete design of my developing software in C++. I really do not want to change the structure.
However, I sometimes get erroneous outputs to store in integer variable. Output is not any number, output is NaN. But I do not want to add any other variable to check whether my integer variable is erroneous or not.
Is there any way to store a thing such as NaN in an integer variable?

It's not magic, it's information theory basics. int is something that stores values in range [INT_MIN, INT_MAX]. That is all it can do, no less no more.
You constrain to use just the int, leaving you the only option to use some value as your indicator. If that is not good enough, you must reconsider the constraint.

No, there is no value that you can store in an integral type which can represent a NaN.
If you need to store this value, you are going to have to reconsider your design. This doesn't necesarrily mean adding a new variable, but you might change an existing one. For example, the int variable where you currently store this value which can be NaN could be changed to something like boost::optional <int>. That way, it could be unset if the value was NaN, or set otherwise.

Related

Best variable types to use for floating-point value [duplicate]

This question already has answers here:
Floating point inaccuracy examples
(7 answers)
Closed 3 years ago.
I have a FLOAT column in a SQL Server database that appears as follows in SQL Server Management Studio.
18.001
When I read that value into a float variable, and format it using sprintf() ("%f"), it appears as:
18.000999
When I read that value into a double variable, and format it using sprintf(), it appears as:
18.001000
Could I get some suggestions on this? The values being stored are generally under 100, with up to 3 decimal places. What is the best SQL Server type? What is the best C++ type? And should I be using some rounding technique to get it in the format I want?
Note: I'm not actually using sprintf(), I'm using CString.Format(), but the expected behavior is the same.
The values being stored are generally under 100, with up to 3 decimal places.
SQL databases support the numeric/decimal (the two are synonyms) types for fixed-point values. For your specific type, you could use decimal(6, 3). That is six significant digits, with three of them to the right of the decimal point. These two values are called scale and precision respectively.
If the values can differ a bit from this, you might want a wider range.
With decimal/numeric, what-you-see-is-what-you-get. I would recommend storing them in the database as fixed-point numbers.
Answering the question on it's face value, assuming floating point should be used and fixed point is not applicable.
Unless you are really tight on memory, there is really no reason to use anything for floating numbers in C++ but double. Float looses precision without giving you much in return. You can also try long double, but in my experience it is rather overkill. Also, if your compiler is MSVC, I have heard it's long doubles are the same as doubles.
In alternative to the fixed comma decimals proposed already, just use ordinary integers!
Instead of storing 18.001 seconds, you'd store 18001 milliseconds, you wouldn't store Euro, Pound, Dollar, but tenth of a cent or penny, ...
Type in C++ would be an integer as well, large enough to hold maximum numbers you need, e. g. uint32_t, int64_t, ...

Should I use an unsigned char instead of an int to store values that will never be greater than 255? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
In a C++ program I am writing for fun there are frequently numeric values being used that will absolutely never be greater than 255, and I am therefore storing them as unsigned chars to save on memory used (as an unsigned char only uses a byte, as opposed to the 4 bytes of an int). Is this a good idea? Are there any downsides to doing this?
I appreciate tips and insight anyone can give.
It's a trade-off.
Given that you are using unsigned char to represent non-negative (presumably) values that don't exceed 255, you will save on memory usage for storing the particular values.
If your code does arithmetic operations on those unsigned char, then the values may be implicitly promoted to int, the operation done using ints, and then the result converted back. This is consistent with the fact that quite a few real-world machines do not have machine registers that work directly with char types, but do have registers and instructions that are optimised for a larger "native" integral type i.e. int. Such to-and-fro conversions can mean that code which does a sequence of operations on unsigned chars can have measurably lower speed than coding to use variables of type int. (Notionally, an implementation might "optimise out" such to-and-fro conversions, if analysis shows there is no change of observable result from a sequence of operations, but it is not required to)
Generally speaking, for representing numeric values, I would suggest not using unsigned char and to default to using int (or another suitable integral type if the range of values you need to represent goes beyond the range that an int is guaranteed able to represent). Get the code working first and, if you decide to optimise your code to save on memory, do testing/profiling on representative target systems to determine the extent of any performance impact of using unsigned char. If using C++11 or later, you might also consider using uint8_t (on implementations that support it) but bear in mind there may be similar trade-offs with that as well.
There isn't really any downside but you might not use lesser memory depending on the order of your member variable definitions because of padding bytes(this only applies to classes).

Convert string to double and then double to string without losing precision [duplicate]

This question already has an answer here:
Set precision of std::to_string when converting floating point values [duplicate]
(1 answer)
Closed 6 years ago.
I am using C++11. I have real world coordinates such as 38.0098662, 23.7805398 in a text file, meaning 2 double variables. I parse that file with C++ and I convert the strings to double with the stod() method. When I tried printing the values with count.precision(9);, the values seemed to be the same as in the text file.
Then, I want to convert those double values back to string format. For that I use to_string() method. However that seems to be changing the value slightly. For example:
38.0098662, 23.7805398 became
38.009866, 23.780540
// in fact, every number is xx.yyyyyy
I don't understand why this is so hard to do with C++11. Why do I lose precision for no reason ? How can I do this properly ? Every question I looked into pointed to to_string() method, which is what I am using.
Someone had the same problem as you had.
Simply set the precision of the std::ostringstream to your desired size and return it as std::string.
Here is a reference to an older question which shows the implementation:
Look at this!
Hope this helps!
It cause from compiler code optimization(for fastest run).
Sometimes C++ compiler optimizes floating point number processing, and loses a bit precision.

How to ensure the function return consistent floating point values in C/C++? [duplicate]

This question already has answers here:
How deterministic is floating point inaccuracy?
(10 answers)
Closed 9 years ago.
How to enure the function return consistent floating point values in C/C++?
I mean: if a and b are of floating point type, if I wrote a polynomial function (which takes floating point argument and returns floating point results), lets call it polyfun(), do the compiler can ensure that:
if a==b, then polyfun(a)==polyfun(b), which means the order of maths ops/rounding up are consistent at runtime?
Reproducible results are not guaranteed by the language standards. Generally, a C implementation is permitted to evaluate a floating-point expression with greater precision than the nominal type. It may do so in unpredictable ways, such as inlining a function call in one place and not another or inlining a function call in two places but, in one place, narrowing the result to the nominal type to save it on the stack before later retrieving it to compare it to another value.
Some additional information is in this question, and there are likely other duplicates as well.
Methods of dealing with this vary by language and by implementation (particularly the compiler), so you might get additional information if you specify what C or C++ implementation you are using, including the details of the target system, and if you search for related questions.
Instead of polyfun(a)==polyfun(b) try ABS(polyfun(a) - polyfun(b)) < 1e-6, or 1e-12 or whatever you find suitably appropriate for "nearness"... (Yeah, cumulative float point errors will still kill you.)

check NaN number [duplicate]

This question already has answers here:
Checking if a double (or float) is NaN in C++
(21 answers)
Closed 1 year ago.
Is it possible to check if a number is NaN or not?
Yes, by use of the fact that a NaN is not equal to any other number, including itself.
That makes sense when you think about what NaN means, the fact that you've created a value that isn't really within your power to represent with "normal" floating point values.
So, if you create two numbers where you don't know what they are, you can hardly consider them equal. They may be but, given the rather large possibility of numbers that it may be (infinite in fact), the chances that two are the same number are vanishingly small :-)
You can either look for a function (macro actually) like isnan (in math.h for C and cmath for C++) or just use the property that a NaN value is not equal to itself with something like:
if (myFloat != myFloat) { ... }
If, for some bizarre reason, your C implementation has no isnan (it should, since the standard mandates it), you can code your own, something like:
int isnan_float (float f) { return (f != f); }
Under Linux/gcc, there's isnan(double), conforming to BSD4.3.
C99 provides fpclassify(x) and isnan(x).
(But C++ standards/compilers don't necessarily include C99 functionality.)
There ought to be some way with std::numeric_limit<>... Checking...
Doh. I should have known... This question has been answered before...
Checking if a double (or float) is NaN in C++
Using NaN in C++?
http://bytes.com/topic/c/answers/588254-how-check-double-inf-nan
you are looking for null, but that is only useful for pointers. a number can't be null itself, it either has a known value that you put in there or random data from whatever was there in memory before.