DEV Community

hassaan-syed
hassaan-syed

Posted on

Why 0.1 + 0.2 != 0.3 in C? Understanding Floating Point Numbers

HISTORY:IEEE 754 was invented in 1985 to standardize floating-point arithmetic, ensuring consistent, reliable, and portable numerical results across different computer hardware.

#include <stdio.h>

int main() {
    float a = 0.1;
    float b = 0.2;

    if (a + b == 0.3)
        printf("Equal\n");
    else
        printf("Not Equal\n");

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

WHAT DO YOU EXPECT?
Eqaul or Not Equal,If Equal then your wrong because,
computer dont know the . as a decimal so for that we usedb IEE754 standard for better uderstanding the real problem let us do by example.

Computers don’t understand numbers like we do.
We use decimal (base 10):
0.1 → one tenth

But computers use binary (base 2):
0s and 1s only

Now here’s the catch:
Some decimal numbers cannot be represented exactly in binary

Just like:
1/3 = 0.3333... (infinite in decimal)

Similarly:
0.1 in binary = 0.0001100110011... (infinite)

then,What is actaully stored in computer
like eg : float 0.1
it stores the nearest approx value
like : 0.10000000149011612 (in binary)

WE CAN PROVE BY CODING

#include <stdio.h>

int main() {
    float a = 0.1;
    float b = 0.2;

    printf("%.20f\n", a);
    printf("%.20f\n", b);
    printf("%.20f\n", a + b);

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT
0.10000000149011611938
0.20000000298023223877
0.30000001192092895508

NOW,lets understand how really its stores in binary so called "Format"
its is simple its stores in 4bytes
this bytes are divided into fixed paths we call as:
1.sign

2.exponent
3.mantisa

this are actaully important so keep in mind

Sign (S)
Decides whether the number is positive or negative
Uses 1 bit only
0 → Positive (+)
1 → Negative (−)

Example:
+5.2 → Sign = 0
-5.2 → Sign = 1

Exponent (E)
Controls the scale (magnitude) of the number
Think of it like moving the decimal point

“How big or how small is the number?”
Higher exponent → Bigger number

Lower exponent → Smaller number

Example idea:
1.23 × 10³ = 1230 (big)
1.23 × 10⁻³ = 0.00123 (small)

In binary, the exponent does the same job.

Fraction / Mantissa (F)
Stores the actual digits (precision) of the number
This is the main value part.

“What are the exact digits of the number?”
More fraction bits → More accuracy

Less fraction bits → Less accuracy

let me ask something?
do you know what is sign copy if yes comment please

THANK YOU FOR READING
"Take it from me that all knowledge is useless until it is connected with your life, because the purpose of knowledge is nothing but to show you the splendors of yourself!"

Top comments (0)