Handle -0 from Database Value in C++ - c++

At present I am working on piece of C++ code in which I need to read data from a database, and if database value is non-zero, then I need to apply some further logic.
But in the database there are values which are being calculated and can come out as -0.0. And this negative zero is being treated as Garbage value in C++ double variable. I have already initialized the value as 0.0 in constructor.
Sample Code:
for(Sample::List<BalanceSheet>::Iterator i((Sample::List<BalanceSheet> &) Balance.Entries()); i.HaveItem(); ++i) // This list is being populated from Database
{
if (SomeCondition != "")
{
if (i->GetBalance() != 0) // This is where am getting Garbage values since GetBalance() returns -0.0
{
DoOperation();
}
}
}

-0.0 is perfectly valid value for a double. The problem you are having is that you are comparing doubles for inequality.
What you should do is something like this:
i->GetBalance() > std::numeric_limits<double>::epsilon()

First off, you should never be using == or != with floating point variables. They are essentially meaningless operations, as the limitations of floating point types mean that even seemingly innocuous values might not compare identically. It is completely possible that 2 + 2 isn't 4, at least as far as == would identify it.
The real issue here is that you are making use of the sign of a "zero" value, which as per above, might not actually be exactly zero in the first place, but more importantly, is difficult to test for using standard comparison operators. See this related question for some discussion.
The best solution for this, if you have access to C++11 or a compiler supporting it, is to use copysign as per Vlad's answer on that question. This function takes 2 parameters. The first represents the magnitude of the return value, and the second the sign. Here is an example:
#include "iostream"
#include <math.h>
using namespace std;
int main()
{
double posZero = +0.0d;
double negZero = -0.0d;
if( copysign( 1, posZero ) < 0 )
{
cout << "posZero is negative\n";
}
else
{
cout << "posZero is positive\n";
}
if( copysign( 1, negZero ) < 0 )
{
cout << "negZero is negative\n";
}
else
{
cout << "negZero is positive\n";
}
}
posZero is positive
negZero is negative
In this example, copysign creates a value of +/- 1, according to the sign on the second argument. The first argument for your purposes could be any non-zero value, but might as well be 1.
Alternatively, you could use signbit, which is honestly probably more direct. A version of the above using this function:
#include "iostream"
#include <math.h>
using namespace std;
int main()
{
double posZero = +0.0d;
double negZero = -0.0d;
if( signbit( posZero ) )
{
cout << "posZero is negative\n";
}
else
{
cout << "posZero is positive\n";
}
if( signbit( negZero ) )
{
cout << "negZero is negative\n";
}
else
{
cout << "negZero is positive\n";
}
}
With the same output.

Related

Handling int and std::vector::size_type in comparsion

So I have something like this (C++03):
class MyClass
{
// ...
}
class something
{
private:
std::vector<MyClass*> container;
// ...
}
// cmdarg can be anything, negative int too...
void something::foo(const std::string& cmdarg)
{
const int res = std::stoi(cmdarg);
if (res >= 0 && static_cast<std::vector<MyClass*>::size_type>(res) < this->container.size())
{
// ...
}
}
I would like to ask if the conversion from int to std::vector<MyClass*>::size_type is valid. The res >= 0 says it's non negative, so I guess converting to an another non-negative number is okey.
My problem is, if I write
if (res >= 0 && res < container.size())
I get a warning, because of comparsion with signed and unsigned integer types.
My above code (the full one) compiles and seems to work, but I'm not sure.
Thank you.
Your code looks a bit too perfect for my taste.
Breaking it down:
const int res = std::stoi(cmdarg);
if (res >= 0 && static_cast<std::vector<MyClass*>::size_type>(res) < this->container.size())
The if-statement for checking below zero is nice. Personally I would write this as:
if (res < 0)
{
std::cerr << "Negative number " << res <<" given for ..., a positive was expected" << std::endl;
return -1;
}
This leads us to the cast:
auto unsigned_res = static_cast<std::vector<MyClass*>::size_type>(res);
However, size_type this vector always size_t as it uses the std::allocator. In code review, I would request to change this for readability to:
auto unsigned_res = static_cast<std::size_t>(res);
Finally, you can indeed nicely compare it:
if (unsiged_res < container.size())
// Do something
Note that I mentioned both the comparison and the cast, as this needs to happen in that order. On top of that, you also need some exception handling for when std::stoi fails, see it's documentation
For more details on how to correctly deal with signed/unsigned, I can recommend this article on ithare.

"Industrial Strength" C++ struct

It's been a while since I used C++. I was asked for job interview to create a C++ struct for a downsampling routine which would meet the following interface:
struct deterministic_sample
{
deterministic_rate( double rate );
bool operator()();
};
-- with the following behaviour:
We have an object of that class: deterministic_sample s;
We call s() N times, and it returns true, M times. M / N is roughly equal to the rate
The sequence is deterministic, not random and should be the same each time
The class should be "industrial strength", for use on a busy stream.
My solution, version 2:
#include <iostream>
#include <cmath>
#include <climits>
using namespace std;
struct deterministic_sample
{
double sampRate;
int index;
deterministic_sample() {
sampRate = 0.1;
index = 0;
}
void deterministic_rate( double rate ) {
this->sampRate = rate; // Set the ivar. Not so necessary to hide data, but just complying with the interface, as given...
this->index = 0; // Reset the incrementer
};
bool operator()() {
if (this->index == INT_MAX) {
this->index = 0;
}
double multiple = this->index * this->sampRate;
this->index++; // Increment the index
if (fmod(multiple, 1) < this->sampRate) {
return true;
} else {
return false;
}
};
};
int main()
{
deterministic_sample s; // Create a sampler
s.deterministic_rate(0.253); // Set the rate
int tcnt = 0; // Count of True
int fcnt = 0; // Count of False
for (int i = 0; i < 10000; i++) {
bool o = s();
if (o) {
tcnt++;
} else {
fcnt++;
}
}
cout << "Trues: " << tcnt << endl;
cout << "Falses: " << fcnt << endl;
cout << "Ratio: " << ((float)tcnt / (float)(tcnt + fcnt)) << endl; // Show M / N
return 0;
}
The interviewer said this v2 code "partly" addressed the requirements. v1 didn't have the constructor (my error), and didn't deal with overflow of the int ivar.
What have I missed here to make this class robust/correct? I think it is some aspect of "industrial strength" that I've missed.
ps. for any ethical types, I've already submitted my second-chance attempt... It's just bothering me to know why this was "partly"...
What you have is far more complex than necessary. All you need to do is keep track of the current position, and return true when it goes past the threshold.
struct deterministic_sample
{
double sampRate;
double position;
deterministic_sample() : sampRate(0.1), position(0.0) {
}
void deterministic_rate( double rate ) {
assert(rate <= 1.0); // Only one output is allowed per input
sampRate = rate; // Set the ivar. Not so necessary to hide data, but just complying with the interface, as given...
// No need to reset the position, it will work with changing rates
};
bool operator()() {
position += sampRate;
if (position < 1.0)
return false;
position -= 1.0;
return true;
}
};
Use unsigned and integer overflow is a well-defined wraparound. This is very fast on normal CPU's.
The second problem I see is the mix of floating-point and integer math. That's not really efficient. It may be more efficient to store multiple as a member and just do multiple += rate. This saves you one integer to double conversion.
However, the fmod is still quite expensive. You can avoid that by keeping int trueSoFar instead. Now the rate so far is double(trueSoFar)/double(index) and you can check double(trueSoFar)/double(index) > rate or more efficiently trueSoFar> int(index * rate). As we already saw, rate*index can be replaced by multiple += rate.
This means we have one double addition (multiple +=), one FP to int conversion int(multiple) and one integer comparison.
[edit]
You can also avoid FP math altogether by keeping a 32/32 rational approximation of rate, and comparing that to the realised rate (again stored as a 32/32 ratio). Since a/b > c/d when a*d > b*c you can use a 64 bit multiply here. Even better, for the target ratio you can choose 2^32 as a fixed denominator (i.e. unsigned long targetRate = rate*pow(2^32), b=2^32 implicit) so that you now have unsigned long(unsigned long long(a)*index) >> 32) > trueSoFar. Even on a 32 bit CPU, this is fairly quick. >>32 is a no-op there.
OK, so it seems there are some improvements to the efficiency which could be made (certainly), that "industrial strength" has some implications though nothing concrete (possibly the problem...), or that the constructor was incorrectly named in the question (also possible).
In any case, no one has jumped on some glaring omission that I made to my constructor (like, I see there are two ways to do a C++ constructor; you should do both to be really bullet-proof, etc.)
I guess I'll just cross my fingers and hope I still progress to the soft-skills interview!
Thanks all.

Write a program that simulates flipping a coin repeatedly and continues until three consecutive heads are tossed, in C++

Write a program that simulates flipping a coin repeatedly and continues until three consecutive heads are tossed, in C++
#include <iostream>
#include <cmath>
#include <string>
#include <cstdlib>
#include "random.h"
using namespace std;
bool FlipCoin(int flip);
int main(){
int flip;
int heads = 0;
int total_flips = 0;
while( heads < 3){
total_flips++;
if(FlipCoin(flip) == "heads"){
heads++;
} else{
heads = 0;
}
}
cout << "it took " << total_flips << "to get 3 consecutive heads. " << endl;
}
bool FlipCoin(int flip) {
if (randomChance(0.50)) {
return "heads";
} else {
return "tails";
}
}
I am getting this error in the main body of my code that states that
ISO C++ forbids comparison between pointer and integer
at the if (FlipCoin(flip) == "heads") part. If anyone can help me correct this that would be great.
Since strings are inefficient and error-prone (one typo and your comparison fails, while the compiler stays absolutely silent) and bools do not represent coin sides very well (is true heads or tails?), the best way to write this is using an enum:
enum class CoinSide { heads, tails };
CoinSide FlipCoin() { // note: you don't need the "flip" parameter
if (randomChance(0.50)) {
return CoinSide::heads;
} else {
return CoinSide::tails;
}
}
int main() {
...
if (FlipCoin() == CoinSide::heads) {
...
}
}
You have defined FlipCoin() with a return type of bool, but you're returning char* from it. You have a couple of options:
Change FlipCoin() to return char*. Then use if (strcmp(FlipCoin(flip), "heads") == 0). "heads" == "heads" works in C/C++, but only because of luck because the compiler optimizes the string table. So the pointers are equal, but it's not exactly correct. strcmp() returns 0 if the strings are equal, non-zero if they are not.
Change FlipCoin to return std::string, then use if (FlipCoin(flip) == "heads").
You should be getting a few compiler warnings from this code, about returning char* from a bool function, and about an unused parameter (flip) being passed into FlipCoin().
You wrote:
bool FlipCoin [....] return "heads";
Do you believe that "heads" / "tails" qualifies as a boolean type?
You should decide if FlipCoin is going to return true / false, or return a string.
After you've resolved that, you can fix your if-statement comparison:
if(FlipCoin(flip) == "heads"){
To either compare against a bool or a string.
But right now, it does not make any sense to declare FlipCoin to return a bool, actually return a string, try to convert the string to a bool, then try to compare the bool to a string.

C++ using 1 function for multiple varaibles. Only first run works

Newish to C++ but been researching alot so please bear with me.
I've been trying to use 1 function to relate 8 global double variables [ mA mB ... mG which ranges from values 1 to 10] to another double value.
I first obtain these 8 variables by obtaining the data from a csv file, throwing them to an array and then equating the set global variables. This all works fine. I cout the values correctly.
mA =10, mB=1 ,.... mG=2
However I need to use these variables to relate to another set value. So i Use:
double Function1(double Mvalue1)
{
if (Mvalue1 == 1) { double value = 10; return value ; }
if (Mvalue1 == 2) { double value = 20; return value ; }
.... // cont to 10 only increasing value by 10
if (Mvalue1 == 10) { double value = 110; return value ; }
}
void VarFunction()
{
mA2= Function1(mA); **//SHOULD output 110**
cout << "Vaule A " << mA2 << endl;
mB2= Function1(mB); **//SHOULD output 10**
cout << "Vaule B " << mB2 << endl;
....//.... 8 times
mG2 = Function1(mG); **//SHOULD output 20**
cout << "Vaule G " << mG2 << endl;
}
int main()
{
VarFunction()
return 0;
}
So the output i get here is
Value A 110
Value B -1.#IND
....
Value G -1.#IND
Why isnt the next call of function1 with the next variable not working?
In your code you have mA set to 12, but Function1 doesn't have a case for 12. So, I'm surprised you're even getting 110 printed for the first line. You aren't handling the case inside Function1 where Mvalue1 isn't one of the desired values, so this is the first thing to fix.
Also, assigning a number to a double and then returning it is unnecessarily complicated. A case statement would work well, assuming you really want to pass integers:
double Function1(int Mvalue1)
{
switch(Mvalue1) {
case 1: return 10;
case 2: return 20;
//...
case 10: return 110; // are you sure you don't want 100?
default: return -1; // handle the case here so that you always return a value.
}
}
Of course, if you really just want 10 times your input, why not:
double Function1(double mValue1)
{
return mValue1*10;
}
Not all paths in your function return a defined value, i.e. there's no return statement after all the conditionals.
The compiler is probably telling you that. If not - compile with higher warning level.
Use the std::map container when building relationships like this.
#include <iostream>
#include <map>
typedef std::map<double, double> rel_t;
int main()
{
rel_t mymap;
// You can directly
// std::map<double, double> mymap;
mymap[1] = 10;
mymap[2] = 20;
mymap[10] = 110;
std::cout << mymap[1] << std::endl; // Prints 10
std::cout << mymap[2] << std::endl; // Prints 20
std::cout << mymap[10] << std::endl; // Prints 110
}
This program seems to be working for me when I run it. However, I had to add declarations for mA2, mB2, and mG2 in your VarFunction(). You're also missing a semicolon after your call to VarFunction() in main().
I'd also suggest you return some default double in the function double Function(double Mvalue1), just in case Mvalue1 does not satisfy any of the if statements.
As already said, Function1() should return a value in case all if statements are false!
If the numbers your are dealing with have no fractional digits, use short, int, long or any other integer type for the variables. Then you can use a switch()/case construct or keep on using the comparison operator ==.
In case you must deal with floating point values, never use the == operator! When reading floating point values from text files (like CSV) or a database, a conversion from text to float/double is done. The result from such conversion can end in e.g. 9.999999999 or 10.000000001 instead of 10. And then the comparison with == is false!
To compare two double variables use a method like this:
bool dEqual( double dVal1, double dVal2, double dTolerance)
{
if( fabs( dVar1 - dVar2) < dTolerance) {
// dVar1 is nearly equal to dVar2
return true;
}
// dVar1 is not equal to dVar2
return false;
}
Then this comparison is true:
if( dEqual( 10.0, 9.999999998, 0.000001))
Apply a value for tolerance that meets the accuracy you need.

How to prevent overflow when using usual math functions exp() log()?

All is in the title. How to check a possible overflow when using the two functions exp() and log()?
#include <errno.h>
When an oferflow occurs, then errno is set to ERANGE.
Next time, do your homework before asking.
Googling: "c++ exp" returned this as the first result http://www.cplusplus.com/reference/cmath/exp/
In the middle of the page, there is EXACTLY what you're looking for.
To expand the answer of #TheOtherGuy, you can cancel the operation if overflow occurs.
#include <stdio.h>
#include <math.h>
#include <errno.h>
int main(void)
{
double param, result;
errno = 0;
param = 1e3;
result = exp (param);
if (errno == ERANGE) {
printf("exp(%f) overflows\n", param);
result = param;
}
printf ("The exponential value of %f is %f.\n", param, result );
return 0;
}
The best way to check for overflow beforehand is to do so intelligently on a case-by-case basis.
Using your knowledge of logarithms and exponents, you should be able to identify potential overflows using properties like INT_MAX: examine these C++ Limitations
I threw a rough sample c++ execution together, assuming you know beforehand what limits you are attempting to follow.
#include <iostream>
// nTh root calculator
bool is_exp_overflow(int input_val, int exponent)
{
my_max = pow(INT_MAX, (1/exponent);
if (input_val > my_max)
{
return true;
}
else
return false;
}
void runExp(int my_input, int my_exp)
{
// Do maths
}
int main()
{
int my_input = 0;
int my_exp = 0;
std::cout << "Enter test value\n";
std::cin >> my_input;
std::cout << "Enter test exponent\n";
std::cin >> my_exp;
bool exp_unsafe = 1;
exp_unsafe = is_exp_overflow(my_input, my_exp);
if (!exp_unsafe)
runExp(my_input, my_exp);
else
std::cout << "Code is unsafe\n";
return 0;
}
If you're looking to catch the errors post mortem, examine errno in range.
For the exp() handling:
Just compare against a variable which you assign to log(FLT_MAX). FLT_MAX is biggest float.
You can do this before calculating an exp(). Because log() is inverse of exp() .
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
float a=1E+37f; // an example of maximum finite representable floating-point number.
//max value can change with platform so,
//either use definitions or use a function you wrote
// a= getMaxFloat(); or a=FLT_MAX
float b=log(a); // limit of float to give in exp();
float c=3242325445.0f; // test variable
cout << "Hello world!" << endl;
if(c>b){cout<<"you should not take exp of "<<c<<endl;}else{cout<<"go on"<<endl;}
return 0;
}
For the log() handling:
1)You cannot everflow log(x) before overflowing x. (for the upper bound)
2)Float's/Double's (x) precision is not enough to overflow to negative-infinity for log(x).
3)Make sure x is bigger than zero.
Better than prevent, you can catch the exception:
try {
z=exp(n);
} catch (...) {
puts("Can't calcute exp...");
}