Hello. I need help with the logical error in finding the GCD of the two numbers that I've committed below. The output should be 0.03 but the output that has been processed by the program is 7.62939e-06. Can someone help me fix the code and explain what should be done with the logical error below? I'm having a hard time analyzing it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <cmath>
usingnamespace std;
float GCD(float a, float b)
{if (a == 0)
return b;
if (b == 0)
return a;
if ( a > b)
return GCD (a-floor(a/b)*b, b);
elsereturn GCD(a, b-floor(b/a)*a); }
int main()
{ cout<<GCD(76.65,65.76); return 0; }
Result: The gcd of 76.65 and 65.76 is 1.4210854715202E-14
0.03 does not appear to be correct. But I dunno. Where did you get your expected answer?
is yours just not quite converging on it, due to ending early? Its headed that way... wat you get with double?
@jonnin this is the proof that the gcd of 76.65 and 65.76 is 0.03 https://lcmgcf.com/gcf-of-decimals-76.65-65.76/ I'm trying my best just to make the output 0.03 but it doesn't even get close to it.
One thing to note about tags, the formatting will NOT work on an initial post before it has been submitted. This is a known bug, not likely to ever get fixed. You can either manually type the tags or edit an already submitted post.
The format buttons work with follow up posts as they should.
@ForgottenLaw
The GCD of two floating-point numbers is nonsense anyway. Even the (non-)proof that you link to does it by turning the numbers into integers first (7665 and 6576), calculating the GCD of those, then dividing by 100 afterwards. This is crazy.
For floating-point numbers in computer code you are going to run into so many problems with round-off error as to make your results meaningless.
Why do you think that std::gcd() is defined only for integers?
This returns 0.03 but the cutoff for 'zero' is going to vary from problem to problem.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
double GCD(double a, double b)
{
if ( fabs(a) < 1e-10)
return b;
elseif (fabs(b) < 1e-10)
return a;
elseif ( a > b)
return GCD (fmod(a,b), b);
elsereturn GCD(a, fmod(b,a));
}
int main()
{ cout<<GCD(76.65,65.76); return 0; }
I am curious if, in general, it always converges to (a sort of equals b) eg ( fabs(a-b) < 1e-100 or so? that appears to happen for THIS problem.
what is happening is that a or b gets 'close to zero' when it finds the result, but its not EQUAL to zero. You can see this by printing a and b each iteration. Therefore your logic is fine, but your numerical methods are out of sorts.
Thank you so much for the information guys. Especially for @jonnin, Now I know what's wrong with my code. The main cause of the logical problem is that because of the fabs().