Floating Point Exception for seemingly no reason [closed] - c++

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 6 years ago.
Improve this question
My code is throwing me a floating point exception here, but I can't figure out why.
int i = this -> numerator;
while(i > 1){
if ((this -> numerator % i == 0) && (this -> denominator % i == 0)) {
this -> numerator = this -> numerator / i;
this -> denominator = this -> denominator / i;
}
i = i - 1;
}
The goal is to simplify a fraction. As you can see, things only get mod by i and i > 1. Same goes for division. Strangely it will keep throwing the error even if I comment out the code within the while loop, but the code works fine if I get rid of the while loop completely. The same thing happened when I tried to use a for loop instead. What am I missing?

Strangely it will keep throwing the error even if I comment out the code within the while loop,
Then your problem is not in this bloc of code. Which, so far, I compiled and run with no error.
but the code works fine if I get rid of the while loop completely
Then, it's likely you are doing something with variable i after this bloc of code that makes the floating point exception.
Run your code with a debugger to check where it fails.

Related

what is happening inside this factorial program? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i was just playing with the factorial question using recursion when i wrote the following code.
i know that i could directly return the factorial.however i created a variable result and wrote the code below.
now what i want to know is that haven't i created n (the no. i want to calculate the factorial of)no. of result variables in the process?? because whenever my function factorial is called ,result variable is created , and each of those result variables would hold some value.
long long factorial(long long param) {
long long result;
if (param == 1) return 1;
else {
result = param * factorial(param - 1);
}
return result;
}
i know this is not a good code and i didn't thought that this would give me the write answer .however to my surprise it is.i want to know what is going on in this program.
Your function is a recursive function. You can read about recursion, and about recursive debugging here:
https://www.programiz.com/cpp-programming/recursion
https://beginnersbook.com/2017/08/cpp-recursion/
First of all : your function is unable to determine 0!
Second, yes, without any optimization from the compiler your program will take up unnecessary resources. The function is called n times and so the stack grows n times. Within each stack frame a temporary result is pushed on the stack.
However, with this program being so small, it is very likely that a minimal compiler effort will optimize that away in a release build.
It is also possible to do a recursion without the stack growing : define your factorial in such a way that there are never temporary values involved. If f(n, a) := n == 0 ? a : f(n-1, n*a) then factorial(n) := f(n, 1)
This recursion just keeps an accumulated result, wich is a fine example of functional programming. The stack needn't grow.

Why is 1e-12 + 1 = 1 in C++, but not in C? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
In C I put in a big number, like 1e-12, in float data and add 1. It's gave me a correct answer.
In C++ I made the same, but when I add 1 to 1e-12, it returns me 1.
float a = 1e-12;
std::cout << "The number is : " << a + 1 << std::endl;
Output:
The number is: 1
I don't have any error messages. The program just returns the wrong result.
(!! 1e-12 + 1 is not equal to 1!!)
Compilers by default take some short-cuts when doing floating-point math. (They typically have a command-line switch to enforce the rules)
In this case, the rule is that the compiler should store the double value 1e-12 as a float in a, and then, in the output statement, add 1 to the stored value.
The optimization is probably that one of the compilers never stored the value; instead, it added 1 to the double value 1e-12. With the higher precision initial value there are more low bits in the fraction part, and that will affect the result of adding 1.
So the results can be different, depending on how the compiler treats those values.
That's just handwaving, though; if this is really important to you, look at the machine code that the compiler generates in both cases to see what's being done differently.

Same program works on macos but fails on windows [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 8 years ago.
Improve this question
Ok, so I am working on an interface on qt, and I am using qtcreator as an IDE. The thing is that the algorithm works normally on mac, but on windows the same program gets an error.
the only difference is the compiler. The compiler I am using on windows is the visual c++, and on mac is clang (I think).
Is it possible that the same algorithm works on mac but doesn't on windows? If so, what problem could it be?
EDIT: I see that I got downvoted. I don't know exactly why. I know already what the error means, vector subscription out of range. The thing is that I don't want to waste time trying to find where the error is because it actually works fine on mac. Also the pc is better than the mac one.
EDIT 2: Indeed it looks like the same code works differently on windows than on mac. Tomorrow I will test it on mac to try to understand this, but the code that changes is this one:
vector<double> create_timeVector(double simulationTime, double step) {
vector<double> time;
time.push_back(0);
double i = 0;
do {
++i;
time.push_back(time[i-1] + step);
} while (time[i] < simulationTime);
return time;
}
The size of the vector that is returned is one size bigger on windows than on the mac. The thing is that I didn't make any changes on the code.
The probable reason why it works differently is that you're using a floating point calculation to determine when the loop is to stop (or keep going, depending on how you look at it).
time.push_back(time[i-1] + step);
} while (time[i] < simulationTime);
You have step as a double, simulationTime as a double, and a vector<double> called time being used. That is a recipe for loops running inconsistently across compilers, compiler optimizations, etc.
Floating point is not exact. The way to make the loops consistent is to not use any floating point calculations in the looping condition.
In other words, by hook or by crook, compute the number of calculations you need by using integer arithmetic. If you need to step 100 times, then it's 100, not a value computed from floating point arithmetic:
For example:
for (float i = 0.01F; i <= 1.0F; i+=0.01F)
{
// use i in some sort of calculation
}
The number of times that loop executes can be 99 times, or it can be 100 times. It depends on the compiler and any floating point optimizations that may apply. To fix this:
for (int i = 1; i <= 100; ++i )
{
float dI = static_cast<float>(i) / 100.0F;
// use dI instead of i some sort of calculation
}
As long as i isn't changed in the loop, the loop is guaranteed to always do 100 iterations, regardless of the hardware, compiler optimizations, etc.
See this: Any risk of using float variables as loop counters and their fractional increment/decrement for non "==" conditions?
vector subscript out of range means that you used [n] on a vector, and n was less than 0 or greater than or equal to the number of elements in the vector.
This causes undefined behaviour, so different compilers may react in different ways.
To get reliable behaviour in this case, one way is to use .at(n) instead of [] and make sure you catch exceptions. Another way is to check your index values before applying them, so that you never access out of bounds in the first place.

C++ program for power but without using pow function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm a newbee in C++ and I'm writing a C++ program that asks the user to input two integers and then it raises the first integer to the power specified by the second integer. For example, if the user enters 5 and 8, the result will be 5 subscript 8, i.e., number five will be raised to the eighth power. The program must not use any pre-defined C++ functions (like pow function) for this task. The program should allow the user to perform another calculation if they so desire. Can anyone help
I'm not going to give you any code, because that won't allow you to truly explore this concept. Rather, you should use this pseudo code to implement something on your own.
Create a function which accepts two inputs, the base and the exponent.
Now there are several ways to go about doing this. You can use efficient bit shifting, but let's start simple, shall we?
answer = base
i = 1
while i is less than or equal to exponent
answer = answer * base
return answer
Simply loop through multiplying the base by itself.
There are other ways that focus on efficiency. Look here to see something that you may want to attempt: are 2^n exponent calculations really less efficient than bit-shifts?
The program must not use any pre-defined C++ functions (like pow function) for this task
You can use some piece of c++ code like follows, to compute xy, without using any predefined function:
int x = 5;
int y = 3;
int result = 1;
for(int i = 0; i < y; ++i)
{
result *= x;
}
cout << result << endl;
Output:
125
See a working sample here.

How can I find out what's changing the return address of a function in c++

I have a program that behaves weirdly and probably has undefined behaviour. Sometimes, the return address of a function seems to be changed, and I don't know what's causing it.
The return address is always changed to the same address, an assertion inside a function the control shouldn't be able to reach. I've been able to stop the program with a debugger to see that when it's supposed to execute a return statement, it jumps straight to the line with the assertion instead.
This code approximates how my function works.
int foo(Vector t)
double sum = 0;
for(unsgined int i=0; i<t.size();++i){
sum += t[i];
}
double limit = bar(); // bar returns a value between 0 and 1
double a=0;
for(double i=0; i<10; i++){
a += f(i)/sum; // f(1)/sum + ... + f(10)/sum = 1.0f
if(a>3)return a;
}
//shoudn'get here
assert(false); // ... then this line is executed
}
This is what I've tried so far:
Switching all std::vector [] operators with .at to prevent accidentily writing into memory
Made sure all return-by-value values are const.
Switched on -Wall and -Werror and -pedantic-errors in gcc
Ran the program with valgrind
I get a couple of invalid read of size 8, but they seem to originate from qt, so I'm not sure what to make of it. Could this be the problem?
The error happens only occasionally when I have run the program for a while and give it certain input values, and more often in a release build than in a debug build.
EDIT:
So I managed to reproduce the problem in a console application (no qt loaded) I then manages to simulate events that caused the problem.
Like some of you suggested, it turns out I misjudged what was actually causing it to reach the assertion, probably due to my lack of experience with qt's debugger. The actual problem was a floating point error in the double i used as a loop condition.
I was implementing softmax, but exp(x) got rounded to zero with particular inputs.
Now, as I have solved the problem, I might rephrase it. Is there a method for checking problems like rounding errors automatically. I.e breaking on 0/0 for instance?
The short answer is:
The most portable way of determining if a floating-point exceptional condition has occurred is to use the floating-point exception facilities provided by C in fenv.h.
although, unfortunately, this is far from being perfect.
I suggest you to read both
https://www.securecoding.cert.org/confluence/display/seccode/FLP04-C.+Check+floating-point+inputs+for+exceptional+values
and
https://www.securecoding.cert.org/confluence/display/seccode/FLP03-C.+Detect+and+handle+floating-point+errors
which concisely address the exact question you are posing:
Is there a method for checking problems like rounding errors automatically.