Here's working code, I used binary search.
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<assert.h>
#define EPS 0.00000001
double div(double a, double b)
{
if( fabs(a-b) < EPS)
return 1;
if( fabs(b) < EPS )
return NAN;
if( fabs(a) < EPS )
return 0;
double sign = (a<0 ? 1 : -1) * (b<0 ? 1 : -1);
a = fabs(a);
b = fabs(b);
double l = 0;
double r = 1;
while( b*r <= a ) { l=r; r=r*2; }
double x;
do {
x = (l+r)/2;
if( fabs(x*b-a) < EPS) return sign * x;
if( x*b > a )
r = x;
else
l = x;
} while(1);
}
int main()
{
srand(time(NULL));
for(int i=0; i<1000; i++) {
double a = 0.001 * (rand() % 1000000) - rand() % 1000;
double b = 0.001 * (rand() % 1000000) - rand() % 1000;
double x = div(a,b);
printf("%.3lf \\ %.3lf = %.3lf (%.3lf) %.3lf\n", a, b, x, a/b,
fabs(x-(a/b)));
if( fabs(x-(a/b)) > EPS) printf("Error!!!\n");
}
}
megha wrote:
> Hi all,
>
> I am looking for the program/algorithm to implement division without
> using divide operator?
>
> Any idea?
>
> Thanks
>
>
> >
>
>
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/algogeeks
-~----------~----~----~----~------~----~------~--~---
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<assert.h>
#define EPS 0.00000001
double div(double a, double b)
{
if( fabs(a-b) < EPS)
return 1;
if( fabs(b) < EPS )
return NAN;
if( fabs(a) < EPS )
return 0;
double sign = (a<0 ? 1 : -1) * (b<0 ? 1 : -1);
a = fabs(a);
b = fabs(b);
double l = 0;
double r = 1;
while( b*r <= a ) { l=r; r=r*2; }
double x;
do {
x = (l+r)/2;
if( fabs(x*b-a) < EPS) return sign * x;
if( x*b > a )
r = x;
else
l = x;
} while(1);
}
int main()
{
srand(time(NULL));
for(int i=0; i<1000; i++) {
double a = 0.001 * (rand() % 1000000) - rand() % 1000;
double b = 0.001 * (rand() % 1000000) - rand() % 1000;
double x = div(a,b);
printf("%.3lf \\ %.3lf = %.3lf (%.3lf) %.3lf\n", a, b, x, a/b, fabs(x-(a/b)));
if( fabs(x-(a/b)) > EPS) printf("Error!!!\n");
}
}