LearnFrenzy
Sign in Take a free test
C

C Programming · Topic 3 of 23

Floating Point Issues Questions and Concepts

  • 4 exercises
  • 40 questions
  • ~60 min
  • Answers explained

Coding Techniques

Floating Point Issues · Study material

Kahan (compensated) summation

Adding many small numbers to a large running total loses their low bits. Kahan summation keeps the lost part in a correction variable and feeds it back in. Here a million additions of 0.1f drift by almost 1% naively and stay exact with Kahan.

#include <stdio.h>

int main(void) {
    float naive = 0.0f, sum = 0.0f, c = 0.0f;
    for (int i = 0; i < 1000000; i++) {
        naive += 0.1f;

        float y = 0.1f - c;          /* Kahan: add back what was lost last time */
        float t = sum + y;
        c = (t - sum) - y;           /* the part of y that did not make it into t */
        sum = t;
    }
    printf("naive %.2f\nkahan %.2f\n", naive, sum);
    return 0;
}

Output

naive 100958.34
kahan 100000.00

Compile without -ffast-math: that option lets the compiler "simplify" the correction away.

Store money as integers

Ten additions of 0.10 do not make exactly 1.0 in binary. Keep amounts as whole paise or cents and convert only for display.

#include <stdio.h>

int main(void) {
    double total = 0.0;
    long cents = 0;
    for (int i = 0; i < 10; i++) {
        total += 0.10;                /* ten coins of 10 paise, in rupees */
        cents += 10;                  /* the same, in whole paise */
    }
    printf("double: %.17g (== 1.0? %s)\n", total, total == 1.0 ? "yes" : "no");
    printf("integer: %ld.%02ld\n", cents / 100, cents % 100);
    return 0;
}

Output

double: 0.99999999999999989 (== 1.0? no)
integer: 1.00

Avoid subtracting nearly equal numbers

When two close numbers are subtracted, their matching leading digits cancel and only the rounding noise remains ("catastrophic cancellation"). Rewrite the formula: 1 − cos x equals 2 sin²(x/2), which has no subtraction.

#include <math.h>
#include <stdio.h>

int main(void) {
    double x = 1e-8;
    printf("%.3e %.3e\n", 1 - cos(x), 2 * pow(sin(x / 2), 2));   /* same maths, different accuracy */
    return 0;
}

Output

0.000e+00 5.000e-17

Printing and reading floating-point values

TaskCode
Fixed decimalsprintf("%.2f", x)
Scientificprintf("%.3e", x)
Shortest sensible formprintf("%g", x)
Exact round-trip (double)printf("%.17g", x)
Read a doublescanf("%lf", &d) – %f is for float
Read a floatscanf("%f", &f)

In printf, %f works for both float and double (floats are promoted); in scanf the two are different.

Good floating-point habits

  • Use double; write float literals with f.
  • Compare with a relative tolerance, not ==.
  • Loop with integer counters and compute the real value from them.
  • Check for isnan()/isinf() where input can be bad.
  • Divide as double when you want a fraction: sum / (double) n.
  • Use fabs() (not abs()) for doubles.
  • Keep money in integers.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C Programming

C programming is the language most computer science courses start with and the foundation of operating systems, embedded devices and compilers. This section helps you learn C properly – data types, operators, control statements, functions, arrays, strings, pointers, structures, memory allocation and files – and then prove it with hundreds of practice questions explained line by line.

Why it matters

  • C teaches how a computer really works: memory, addresses and how data is stored
  • Pointers and memory questions are a favourite in written tests and technical interviews
  • Once you know C, learning C++, Java and Python becomes much easier
  • Embedded systems, operating systems and many companies' coding rounds still use C

Who it is for

  • School students (Class 11–12 computer science) building a strong programming base
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, aptitude-cum-coding tests and technical interviews
  • Anyone preparing for GATE CS or government IT exams

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro tests
  • Technical interviews
  • GATE CS
  • University exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links