3. Here\'s a short C program: /* This program uses the pow function, which is pa
ID: 3627210 • Letter: 3
Question
3. Here's a short C program:/* This program uses the pow function, which is part of the run-time
math library. To enable its use, this file (fpointHwk.c) was
compiled/linked as follows:
gcc -o fpointHwk -lm fpointHwk.c
In "-lm", that's a lowercase L rather than a one.
*/
#include <stdio.h>
#include <math.h>
int main() {
/* first printf statements */
double d1 = 1.0 / 10.0;
printf("d1 == %f ", d1);
double d2 = pow(2.0, -20.0) * d1;
printf("d2 == %f ", d1);
double d3 = 9.54 * pow(10.0, -8.0);
printf("d3 == %f ", d1);
printf(" ");
/* second printf statements */
if (d1 == d2) printf("d1 == d2 ");
else printf("d1 != d2 ");
if (d1 == d3) printf("d1 == d3 ");
else printf("d1 != d3 ");
if (d2 == d3) printf("d2 == d3 ");
else printf("d2 != d3 ");
return 0;
}
Here's the output:
d1 == 0.100000
d2 == 0.100000
d3 == 0.100000
d1 != d2
d1 != d3
d2 != d3
Explain what's going on. In particular, the first printf statements give the
same value for d1, d2, and d3: 0.100000. However, the comparisons using ==
all evaluate to false, as shown in the second group of printf statements.
Explain, then, why the system thinks that d1 != d2 and so on.
Explanation / Answer
The interesting case involves d2 and d3. For each, the externalrepresentation (that is, what printf outputs) is 0 to six places, thatis,.000000This is the printf("%f",...) output but C also has a %e, which is moresuitable in this case. If you change to printf("%e",...) you'll getd1 == 0.100000d2 == 9.536743e-08d3 == 9.540000e-08which is a far better external representation and which, of course, showsthat d2 != d3.If you take the comparison to the bit level, it's even clearer. Here's the hexdump of d2 and d3, using show_bytesBE ('big endian'):d2: 3e 79 99 99 99 99 99 9ad3: 3e 79 9b d6 8c 73 7e 42Both d2 and d3 are doubles (IEEE 754 extended floating-point types), which havea fractional part of 52 bits and an exponent of 11 bits. Recall that each hexdigit is four binary digits. Starting from the right, it's clear frominspection that the two numbers differ in the rightmost hex paird2: 9ad3: 42Indeed, the rightmost 4 bits differ: a in d2 is 1010, whereas 2 in d3 is 0010.These digits clearly belong to the fractional part or significand. Thereare further differences, of course, but this difference is sufficient. It'sworth noting that the sign, exponent fields, and high-order significand bitsare identical in the two. The problem is that printf("%f",...) doesn't capturethe difference.In summary, although the %f external representation does not capture thedifference in the internal (that is, binary) representation, thebitwise == comparison and the %e external representation do capture thedifference.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.