/* =============================================================================
 * 02_floats_are_not_reals.c  --  Reality #1b: floating-point numbers are an
 *                                ordered-but-rounded set, NOT the real numbers.
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - Is (x + y) + z == x + (y + z) for floats?  (NO -- the famous example
 *     (1e20 + -1e20) + 3.14  vs  1e20 + (-1e20 + 3.14).)
 *   - Is x*x >= 0 for floats?  (Yes -- floats DO keep this one, so it is the
 *     mirror image of the integer case in demo 01.)
 *   - Why does 0.1 + 0.2 != 0.3 ?
 *
 * [How to build & run]
 *   make  &&  ./02_floats_are_not_reals
 *   cc -O2 -o 02 02_floats_are_not_reals.c && ./02
 *
 * [How to read the output]
 *   Each PART states a property and shows whether floating point keeps it.
 *   We print extra digits (%.17g) so you can SEE the rounding, and we print the
 *   raw bits so you can see there is nothing random going on.
 *
 * [Systems link / CS:APP 2.4]
 *   A C `double` is 64 bits of IEEE-754: 1 sign bit, 11 exponent bits, 52
 *   fraction bits. It represents a number as (+/-) 1.fraction x 2^exponent --
 *   a sign, a scale, and ~15-17 significant decimal digits of precision. The
 *   key consequence: results are ROUNDED to the nearest representable value
 *   after every operation. Rounding is not associative, because WHEN you round
 *   changes the answer. But floating point IS monotonic and sign-respecting --
 *   an "ordering" structure -- so x*x >= 0 and comparisons behave sanely. This
 *   is the exact opposite trade-off from integers (demo 01), which are
 *   associative but can overflow into the wrong sign.
 * -------------------------------------------------------------------------- */

#include <stdio.h>
#include <string.h>   /* memcpy: copy raw bytes between two objects            */
#include <stdint.h>   /* uint64_t                                              */

/* ---------------------------------------------------------------------------
 * bits_of  --  reinterpret the 8 bytes of a double as a 64-bit integer.
 *
 * [Idea]
 *   A double and a uint64_t are both 8 bytes. memcpy lets us look at the SAME
 *   bytes two ways: as a number, and as a bit pattern we can print in hex. This
 *   is how you prove the result is a specific IEEE value, not "noise".
 * [Parameters] d -- the double to inspect.
 * [Returns] its 64-bit representation as an unsigned integer.
 * [Edge cases] none; memcpy of equal, fixed size is always safe and is the
 *   correct, portable way to type-pun (casting a double* to a uint64_t* would
 *   be undefined behavior -- a "strict aliasing" violation).
 * ------------------------------------------------------------------------- */
static uint64_t bits_of(double d) {
    uint64_t u;
    memcpy(&u, &d, sizeof u);   /* copy all 8 bytes verbatim                   */
    return u;
}

int main(void) {
    printf("=== Demo 02: floats are not reals (ordered + rounded) ===\n");
    printf("A double is %zu bytes = 1 sign + 11 exponent + 52 fraction bits,\n",
           sizeof(double));
    printf("so ~15-17 significant decimal digits; every op rounds to nearest.\n\n");

    /* ---- PART 1: associativity FAILS (the CS:APP example) ---------------- */
    printf("PART 1: Is (x + y) + z == x + (y + z) for doubles?  (NO)\n");
    volatile double x = 1e20, y = -1e20, z = 3.14;   /* volatile: no folding   */
    double left  = (x + y) + z;   /* 1e20 + -1e20 = 0 exactly, then + 3.14     */
    double right = x + (y + z);   /* -1e20 + 3.14 rounds back to -1e20, then   */
                                  /* + 1e20 = 0; the 3.14 is LOST              */
    printf("  x=1e20, y=-1e20, z=3.14\n");
    printf("  (x+y)+z = %.17g   bits=0x%016llx\n",
           left,  (unsigned long long)bits_of(left));
    printf("  x+(y+z) = %.17g   bits=0x%016llx\n",
           right, (unsigned long long)bits_of(right));
    printf("  equal? %s  -- adding 3.14 to 1e20 changes nothing: it is below the\n",
           left == right ? "YES" : "NO");
    printf("         last representable bit at that scale, so it rounds away.\n\n");

    /* ---- PART 2: x*x >= 0 HOLDS for floats ------------------------------- */
    printf("PART 2: Is x*x >= 0 for doubles?  (YES -- floats keep this one)\n");
    double vals[] = {1e300, -1e300, 3.14, -0.0};
    for (int i = 0; i < (int)(sizeof(vals)/sizeof(vals[0])); i++) {
        volatile double v = vals[i];
        double sq = v * v;              /* may overflow to +inf, never negative */
        printf("  (%-9g)^2 = %-12g  %s\n",
               vals[i], sq, sq >= 0 ? "(>= 0)" : "(NEGATIVE?!)");
    }
    printf("  Lesson: overflow produces +inf, not a wrapped negative. Floats are\n");
    printf("          an ORDERING structure: monotonic, sign-respecting.\n\n");

    /* ---- PART 3: 0.1 + 0.2 != 0.3 ---------------------------------------- */
    printf("PART 3: Why 0.1 + 0.2 != 0.3\n");
    volatile double p = 0.1, q = 0.2, r = 0.3;
    double sum = p + q;
    printf("  0.1 + 0.2 = %.17g\n", sum);
    printf("  0.3       = %.17g\n", r);
    printf("  equal? %s  -- 0.1, 0.2, 0.3 are each infinite in binary (like 1/3\n",
           sum == r ? "YES" : "NO");
    printf("         in decimal), so each is already rounded before we even add.\n\n");

    /* ---- Observations ---------------------------------------------------- */
    printf("Observations:\n");
    printf("  * Floating-point addition is NOT associative: rounding happens after\n");
    printf("    every op, and when you round changes the result. Never test floats\n");
    printf("    with ==; compare |a-b| against a tolerance.\n");
    printf("  * But floats ARE monotone and sign-correct: x*x >= 0 always. This is\n");
    printf("    the mirror image of ints (demo 01): ints are associative but can\n");
    printf("    overflow to the wrong sign; floats keep sign/order but lose\n");
    printf("    associativity to rounding.\n");
    printf("  * The bit patterns prove it is deterministic rounding, not noise.\n");
    return 0;
}
