Improved icky[tm] divider:
#include <stdio.h>
#include <math.h>
#include <float.h>
/*
Icky[tm] division. Use at your own peril.
*/
int double_compare(double d1, double d2)
{
if (d1 > d2)
if ((d1 - d2) < fabs(d1 * DBL_EPSILON))
return 0;
else
return 1;
if (d1 < d2)
if ((d2 - d1) < fabs(d2 * DBL_EPSILON))
return 0;
else
return -1;
return 0;
}
double divide(double x, double y)
{
double y1;
double y2 = DBL_MAX;
double delta;
int i;
y1 = 0.001; /* A horrible estimate just so it will
* be fun to watch in the debugger. */
for (i = 0; i < 100; i++) {
y1 *= (2 - y * y1);
if (double_compare(y2, y1) == 0)
break;
y2 = y1;
}
return x * y1;
}
double divide2(double x, double y)
{
return pow(10.0, log10(x) - log10(y));
}
double divide3(double x, double y)
{
return exp(log(x) - log(y));
}
int main(void)
{
char sx[25];
char sy[25];
double x,y;
printf("result of Newton division of %f by %f is:%f\n", 1.0, 2.0,
divide(1.0, 2.0));
printf("result of Newton division of %f by %f is:%f\n", 1.0, 17.0,
divide(1.0, 17.0));
printf("result of Newton division of %f by %f is:%f\n", 3.0, 19.0,
divide(3.0, 19.0));
printf("result of Newton division of %f by %f is:%f\n", 19.0, 3.0,
divide(19.0, 3.0));
printf("result of Newton division of %f by %f is:%f\n", 12.5,
13.5, divide(12.5, 13.5));
printf("result of Naperian log division of %f by %f is:%f\n", 1.0,
2.0, divide2(1.0, 2.0));
printf("result of Naperian log division of %f by %f is:%f\n", 1.0,
17.0, divide2(1.0, 17.0));
printf("result of Naperian log division of %f by %f is:%f\n", 3.0,
19.0, divide2(3.0, 19.0));
printf("result of Naperian log division of %f by %f is:%f\n",
19.0, 3.0, divide2(19.0, 3.0));
printf("result of Naperian log division of %f by %f is:%f\n",
12.5, 13.5, divide2(12.5, 13.5));
printf("result of Natural log division of %f by %f is:%f\n", 1.0,
2.0, divide3(1.0, 2.0));
printf("result of Natural log division of %f by %f is:%f\n", 1.0,
17.0, divide3(1.0, 17.0));
printf("result of Natural log division of %f by %f is:%f\n", 3.0,
19.0, divide3(3.0, 19.0));
printf("result of Natural log division of %f by %f is:%f\n", 19.0,
3.0, divide3(19.0, 3.0));
printf("result of Natural log division of %f by %f is:%f\n", 12.5,
13.5, divide3(12.5, 13.5));
puts("Your turn, give me x:");
fgets(sx, sizeof sx, stdin);
x = atof(sx);
retry:
puts("Give me y {must not be 0}:");
fgets(sy, sizeof sy, stdin);
y = atof(sy);
if (y == 0) goto retry;
printf("result of Newton division of %f by %f is:%f\n", x, y,
divide(x, y));
printf("result of Naperian log division of %f by %f is:%f\n", x,
y, divide2(x, y));
printf("result of Natural log division of %f by %f is:%f\n", x, y,
divide3(x, y));
return 0;
}