Code is not asking for the tangent of 90°, but the tangent of a number, in radians, close to 90°. The conversion to radians is not exact since π/2 radians is not representable exactly as a double
.
The solution is to perform degrees range reduction first and then call tan(d2r(x))
.
#include <math.h>
static double d2r(double d) {
return (d / 180.0) * ((double) M_PI);
}
double tand(double x /* degrees */) {
if (!isfinite(x)) {
return tan(x);
} else if (x < 0.0) {
return -tand(-x);
}
int quo;
double x45 = remquo(fabs(x), 90.0, &quo);
//printf("%d %f ", quo & 3, x45);
switch (quo % 4) {
case 0:
return tan(d2r(x45));
case 1:
return 1.0 / tan(d2r(- x45));
case 2:
return -tan(d2r(-x45));
case 3:
return -1.0 / tan(d2r(x45));
}
return 0.0;
}
#define PI 3.14159265
int main(void) {
double param, result;
param = 90.0;
result = tan(param * PI / 180.0);
printf("Angle %.*e radian\n", DBL_DECIMAL_DIG - 1, param * PI / 180.0);
printf("Pi/2 = 1.5707963267948966192313216916398...\n");
printf("The tangent of %f degrees is %f.\n", param, result);
int i;
for (i = -360; i <= 360; i += 30) {
printf("The tangent method 1 of %.1f degrees is %.*e\n",
1.0*i, DBL_DECIMAL_DIG - 1, tan(d2r(-i)));
printf("The tangent method 2 of %.1f degrees is %.*e\n",
1.0*i, DBL_DECIMAL_DIG - 1, tand(-i));
}
return 0;
}
OP's output
Angle 1.5707963250000001e+00 radian
Pi/2 = 1.5707963267948966192313216916398...
The tangent of 90.000000 degrees is 557135183.943528.
Better results
The tangent method 1 of -360.0 degrees is -2.4492935982947064e-16
The tangent method 2 of -360.0 degrees is 0.0000000000000000e+00
The tangent method 1 of -330.0 degrees is -5.7735026918962640e-01
The tangent method 2 of -330.0 degrees is -5.7735026918962573e-01
The tangent method 1 of -300.0 degrees is -1.7320508075688770e+00
The tangent method 2 of -300.0 degrees is -1.7320508075688774e+00
The tangent method 1 of -270.0 degrees is 5.4437464510651230e+15
The tangent method 2 of -270.0 degrees is -inf
The tangent method 1 of -240.0 degrees is 1.7320508075688752e+00
The tangent method 2 of -240.0 degrees is 1.7320508075688774e+00
The tangent method 1 of -210.0 degrees is 5.7735026918962540e-01
The tangent method 2 of -210.0 degrees is 5.7735026918962573e-01
The tangent method 1 of -180.0 degrees is -1.2246467991473532e-16
The tangent method 2 of -180.0 degrees is 0.0000000000000000e+00
...