2

I'm trying to code a program to write a fraction m/n as a sum of different Egyptian Fractions (EFs) with the minimal number of EFs.

Here is my full code:

#include<bits/stdc++.h>
using namespace std;
int main(){
    float a,b,sum=0,sct[100000];
    float arr=1; 
    int stt=0;
    cin>>a>>b;
    while(sum!=a/b){  
        sum=sum+(1/arr);
        float dif=a/b-sum;
        printf("%f - sum = %f - dif = %f\n",arr,sum,dif);
        if(dif>=0){
            sct[stt]=arr;
            cout<<"1/"<<arr<<"\n"; 
            stt++;
        } else {  
            sum=sum-(1/arr);
        }
        arr++;
    }
    cout<<stt<<"\n";
    for(int m=0;m<stt;m++) cout<<sct[m]<<" ";
}

You can see well that if dif==0 then the process will end. But when arr==3, I get dif==-0.000000 but the process doesn't end!

Output Caption:

I tried to fix it but all my efforts are useless. Do you know what should I change in my code?

Any help will be high appreciated!

  • Floating point numbers are *not* exact. You generally always want to use `<=` or `>=` when comparing `float`s or `double`s - or compare with some epsilon - very rarely is `==` what you want. See also https://stackoverflow.com/questions/588004/is-floating-point-math-broken and https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Jesper Juhl Oct 13 '18 at 16:08
  • See also https://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout - for debugging purposes. – user202729 Oct 13 '18 at 16:15
  • 1
    FWIW, instead of an image, rather copy the text from the console and post that. Just format it as code and it will be readable. – Rudy Velthuis Oct 13 '18 at 16:36
  • Don't include implementation details (``), include proper C++ headers. – Matthieu Brucher Oct 13 '18 at 16:57
  • Omg, I tried and I am still not successful :( –  Oct 13 '18 at 18:22

1 Answers1

1

Floating point comparisons usually won’t work, because == means “exactly zero”, while you only care that it’s “close enough” to zero. Write a function to check for loop termination:

bool isNear(float f, float g) {
  return abs(f-g)<=((abs(f)+abs(g))/1e8);
}

And use it:

while (!isNear(sum, a/b)) …
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313