Currently I'm new with C and for a course I'm doing an assignment. The assignment is to write two programs that calculate tan(x)
with x
incrementing from 0 to pi/2. One program has to work with float numbers and the other program needs to work with double precision numbers. The goal of the assignment is to become aware of the differences in output, since it's part of scientific programming course.
So far I wrote this program:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
double x;
double pi;
pi = M_PI;
for (x = 0; x <= pi / 2; x += pi / 20)
{
printf("x = %f, tan = %f\n", x, tan(x));
}
exit(0);
}
I got feedback that the output is double. Yesterday I started a thread related to this code, but since different questions rose up, it seemed appropriate to start a new one.
The general principal of the loop works, but I'm stuck in what to do next.
Let's first work on the double-version of the program. Since I need to calculate tan(x)
and x
is not 100% exact, due to the decimal incrementation, I think it's important to define the variables as double. Yesterday I learnt that the output of the printf function is double. Therefore I assume that code is correct for the goal to calculate in double.
Here I have a little side question. I also printed .20f
and it gave me that specific window. I learned a bit about 32- and 64-bit. Double is 64-bit and can store 15 decimal places in the memory.
Question: Has the above code achieved the double precision goal?
Question: Where do the other decimals (16th to 20th) come from if the memory was already exceeded?
For the float version of the program, I need to define the variables as float.
double x;
double pi;
becomes
float x;
float pi;
Then comes the printf statement and here it becomes a bit confusing, because I know now that the printf function gives output in double precision. But I want single precision and still get it printed. I couldn't find another function that specifically prints in single precision.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
float x;
float pi;
pi = M_PI;
for (x = 0; x <= pi / 2; x += pi / 20)
{
printf("x = %f, tan = %f\n", x, tan(x));
}
exit(0);
}
Question: How do I print in single precision?
Question: What do I need to change in the last program to achieve the goal of the float-program?
I'm eager to learn, but it's a bit hard since we're not allowed at the university anymore due Covid-19. I hope someone could give me feedback.
Thanks, Ter