/*
* hodge-podge of mathematical functions
*
* Matt Bishop
* -- May 22, 2024 original program
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <errno.h>
/*
* a useful constant
*/
#define PI 3.141592653
/*
* prototypes
* this is supposed to be defined in math.h but it isn't
*/
int isnan(double); /* true if argument is not a valid float or double */
/*
* start here
*/
int main(void)
{
double x, y; /* used to hold various values */
/* first get the floor and ceiling of a double */
printf("\nGet the floor and ceiling of 7.28:\n");
printf("ceil(7.28) = %f\n", ceil(7.28));
printf("floor(7.28) = %f\n", floor(7.28));
/* now floating point absolute value */
printf("\nGet the absolute value of 3.14 and then -3.14:\n");
printf("fabs(3.14) = %f\n", fabs(3.14));
printf("fabs(-3.14) = %f\n", fabs(-3.14));
/* now log base 10 and exponentiation */
printf("\nGet the log base 10 of 34.6, and raise 10 back to that power:\n");
x = log10(34.6);
y = pow(10, x);
printf("log10(34) = %f -- pow(10, %f)\n", x, y);
printf("but don't compare floats or doubles: pow(10, log10(34.6)) %s 34.6\n", y == 34.6 ? "==" : "!=");
/* remainder for doubles */
printf("\nGet the remainder of 8.2 when divided by 4.1 and 4:\n");
printf("fmod(8.2, 4.1) = %f\n", fmod(8.2, 4.1));
printf("fmod(8.2, 4) = %f\n", fmod(8.2, 4));
/* get fraction, integer parts of a double */
printf("\nGet the integer and fraction parts of 8.21349:\n");
x = modf(8.2, &y);
printf("modf(8.2, &y) = %f, so the integer part is %f and the fraction part is %f (or %d)\n", x, x, y, (int) y);
/* take the square root of 123.456 */
printf("\nGet the square root of 123.456:\n");
printf("sqrt(123.456) = %f\n", sqrt(123.456));
/* now some trig */
printf("\nGet the sine of pi/6 = %f, and then invert it to get pi:\n", PI / 6);
x = sin(PI/6);
y = asin(x);
printf("sin(pi/6) = %f; asin(%f) = %f; and 6*asin(%f) = %f\n", x, x, y, y, 6 * y);
printf("\nGet the cosine of pi/6 = %f, and then invert it to get pi:\n", PI / 6);
x = cos(PI/6);
y = acos(x);
printf("cos(pi/6) = %f; acos(%f) = %f; and 6*acos(%f) = %f\n", x, x, y, y, 6 * y);
printf("\nGet the tangent of pi/6 = %f, and then invert it to get pi:\n", PI / 6);
x = tan(PI/6);
y = atan(x);
printf("tan(pi/6) = %f; atan(%f) = %f; and 6*atan(%f) = %f\n", x, x, y, y, 6 * y);
/* finally, show what happens when you get something that's not a number */
printf("\nNow we show something that is not a number, namely the square root of -1:\n");
errno = 0; /* make sure it is cleared */
x = sqrt(-1.0);
printf("sqrt(-1) = %f", x);
if (isnan(x))
printf(" -- and here is the system error: '%s'\n", strerror(errno));
/* all done! */
return(0);
}
|
ECS 36A, Programming & Problem Solving Version of April 2, 2024 at 12:13PM
|
You can get the raw source code here. |