SlideShare une entreprise Scribd logo
1  sur  1
Télécharger pour lire hors ligne
The Joy of
Programming
How ‘C’mart Are You?                                                                                            S.G. GANESH




A peek into those curious numbers that float in the air.



T
       he discussion assumes that the underlying platform       with double precision.
       supports the IEEE 754 standard for floating point            Note that the binary representation of floating point
       arithmetic. Determine the output of the following        numbers (also in the IEEE 754 standard) has limitations in
two programs:                                                   the range of values it can represent and the accuracy of
                                                                the representation. Practical implication of this is that the
 // Program I                                                   simple arithmetic calculations and comparisons can fail; for
 #include <assert.h>                                            example, 0.9 + 0.5 need not be equal to 1.4, nor




                                                                                                                       GUEST COLUMN
                                                                0.900001—0.9 needs to be equal to 0.000001;
 int main() {                                                   because of that, related calculations can have
 float f = 0.0;                                                 gross errors (for example, floor(3.1—0.1) is not
         int i;                                                 3). For the same reason, the cumulative effect of
         for(i = 0; i < 1000; i++)                              the arithmetic operations can be wrong.
                      f += 0.001;                                   So, direct comparisons of the floating point
         assert(f == 1.000);                                    numbers should not be done and assumptions
 }                                                              should not be made on the accuracy of the values,
                                                                as is done in the usual (decimal) mathematics.
 // Program II                                                  This fact is illustrated by the first program in
 #include <stdio.h>                                             which, if you add 0.001 a thousand times, it’s not
                                                                equal to 1.0 (but is little less than that—
 int main() {                                                   0.999991); hence, the assertion failure!
     printf(“loop starts now...n”);                                Now let’s move on to the second program.
     for(float f = 0.0; f < 20000000.0; f++)                    Since floating point arithmetic is not accurate, the
         ; // just loop over, do nothing                        operations can result in loss of precision and
     printf(“...done!”);                                        rounding errors. In the loop, when the value of f
 }                                                              reaches 16777216.0, adding 1 doesn’t increment
                                                                the value of f by 1, but gets rounded off. You can
   “Ah, easy...” you say! But let’s see the answers first.      verify it with the following code segment:
Program I fails with the assertion failure and Program II
gets into an infinite loop after printing:                       float f = 16777216.0;
                                                                 assert(f == (f + 1));
 “loop starts now...n”.
                                                                    This doesn’t fail with an assertion failure and works
    Before seeing the explanation, let’s have a quick           fine! Now you know why it’s a bad idea to use floating point
tutorial on floating point numbers.                             numbers in loops!
    The types that can represent the numbers with decimal
points (where the position of the decimal point is not
fixed, or in other words, is floating) are known as floating     S.G. Ganesh is an engineer in Hewlett-Packard’s C++
point numbers. There is a standard available for specifying      compiler team. He has authored a book “Deep C” (ISBN 81-
                                                                 7656-501-6). He is also a member of the ANSI/ISO C++
the implementation of floating point numbers (The IEEE
                                                                 Standardisation committee (JTC1/SC22/WG21)
754 Floating Point Standard). Based on that, typically, C
                                                                 representing HP. You can reach him at
compilers support float for representing single precision        sgganesh@gmail.com.
numbers and double type for representing the numbers


                                                                  www.linuxforu.com   |   LINUX FOR YOU   |   FEBRUARY 2007   119


                                                         CMYK

Contenu connexe

Tendances

Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
Mainak Sasmal
 
C programs
C programsC programs
C programs
Minu S
 
Matlab code of chapter 4
Matlab code of chapter 4Matlab code of chapter 4
Matlab code of chapter 4
Mohamed El Kiki
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’
eShikshak
 
Dam31303 dti2143 lab sheet 7
Dam31303 dti2143 lab sheet 7Dam31303 dti2143 lab sheet 7
Dam31303 dti2143 lab sheet 7
alish sha
 
9. pointer, pointer & function
9. pointer, pointer & function9. pointer, pointer & function
9. pointer, pointer & function
웅식 전
 

Tendances (20)

Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
 
C programs
C programsC programs
C programs
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C Programming
 
The solution manual of c by robin
The solution manual of c by robinThe solution manual of c by robin
The solution manual of c by robin
 
Lab 2
Lab 2Lab 2
Lab 2
 
Matlab code of chapter 4
Matlab code of chapter 4Matlab code of chapter 4
Matlab code of chapter 4
 
week-1x
week-1xweek-1x
week-1x
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’
 
week-10x
week-10xweek-10x
week-10x
 
Dam31303 dti2143 lab sheet 7
Dam31303 dti2143 lab sheet 7Dam31303 dti2143 lab sheet 7
Dam31303 dti2143 lab sheet 7
 
C Programming
C ProgrammingC Programming
C Programming
 
C programming
C programmingC programming
C programming
 
9. pointer, pointer & function
9. pointer, pointer & function9. pointer, pointer & function
9. pointer, pointer & function
 
Space Time Varying Color Palettes
Space Time Varying Color PalettesSpace Time Varying Color Palettes
Space Time Varying Color Palettes
 
Chowtodoprogram solutions
Chowtodoprogram solutionsChowtodoprogram solutions
Chowtodoprogram solutions
 
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
 
Computer Architecture and Organization lab with matlab
Computer Architecture and Organization lab with matlabComputer Architecture and Organization lab with matlab
Computer Architecture and Organization lab with matlab
 
Things to avoid in JavaScript
Things to avoid in JavaScriptThings to avoid in JavaScript
Things to avoid in JavaScript
 
Matlab project
Matlab projectMatlab project
Matlab project
 
Conversion of Infix to Prefix and Postfix with Stack
Conversion of Infix to Prefix and Postfix with StackConversion of Infix to Prefix and Postfix with Stack
Conversion of Infix to Prefix and Postfix with Stack
 

Similaire à 02 Jo P Feb 07

Qust & ans inc
Qust & ans incQust & ans inc
Qust & ans inc
nayakq
 
C language questions_answers_explanation
C language questions_answers_explanationC language questions_answers_explanation
C language questions_answers_explanation
srinath v
 
Concept_of_NAN_IND_INF_DEN_Using_C++
Concept_of_NAN_IND_INF_DEN_Using_C++Concept_of_NAN_IND_INF_DEN_Using_C++
Concept_of_NAN_IND_INF_DEN_Using_C++
Mohammed Nisamudheen
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
Amit Kapoor
 

Similaire à 02 Jo P Feb 07 (20)

14 Jo P Feb 08
14 Jo P Feb 0814 Jo P Feb 08
14 Jo P Feb 08
 
Qust & ans inc
Qust & ans incQust & ans inc
Qust & ans inc
 
C language questions_answers_explanation
C language questions_answers_explanationC language questions_answers_explanation
C language questions_answers_explanation
 
Concept_of_NAN_IND_INF_DEN_Using_C++
Concept_of_NAN_IND_INF_DEN_Using_C++Concept_of_NAN_IND_INF_DEN_Using_C++
Concept_of_NAN_IND_INF_DEN_Using_C++
 
Programming basics
Programming basicsProgramming basics
Programming basics
 
Understand more about C
Understand more about CUnderstand more about C
Understand more about C
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptx
 
Programming in C
Programming in CProgramming in C
Programming in C
 
7 functions
7  functions7  functions
7 functions
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2
 
13 Jo P Jan 08
13 Jo P Jan 0813 Jo P Jan 08
13 Jo P Jan 08
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
Looping statements
Looping statementsLooping statements
Looping statements
 
C operators
C operatorsC operators
C operators
 
Deep C Programming
Deep C ProgrammingDeep C Programming
Deep C Programming
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)
 

Plus de Ganesh Samarthyam

Plus de Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 

Dernier

TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 
Microsoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdfMicrosoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdf
Overkill Security
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)
Wonjun Hwang
 

Dernier (20)

TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxCyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
Microsoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdfMicrosoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdf
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
Navigating the Large Language Model choices_Ravi Daparthi
Navigating the Large Language Model choices_Ravi DaparthiNavigating the Large Language Model choices_Ravi Daparthi
Navigating the Large Language Model choices_Ravi Daparthi
 
CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)
 

02 Jo P Feb 07

  • 1. The Joy of Programming How ‘C’mart Are You? S.G. GANESH A peek into those curious numbers that float in the air. T he discussion assumes that the underlying platform with double precision. supports the IEEE 754 standard for floating point Note that the binary representation of floating point arithmetic. Determine the output of the following numbers (also in the IEEE 754 standard) has limitations in two programs: the range of values it can represent and the accuracy of the representation. Practical implication of this is that the // Program I simple arithmetic calculations and comparisons can fail; for #include <assert.h> example, 0.9 + 0.5 need not be equal to 1.4, nor GUEST COLUMN 0.900001—0.9 needs to be equal to 0.000001; int main() { because of that, related calculations can have float f = 0.0; gross errors (for example, floor(3.1—0.1) is not int i; 3). For the same reason, the cumulative effect of for(i = 0; i < 1000; i++) the arithmetic operations can be wrong. f += 0.001; So, direct comparisons of the floating point assert(f == 1.000); numbers should not be done and assumptions } should not be made on the accuracy of the values, as is done in the usual (decimal) mathematics. // Program II This fact is illustrated by the first program in #include <stdio.h> which, if you add 0.001 a thousand times, it’s not equal to 1.0 (but is little less than that— int main() { 0.999991); hence, the assertion failure! printf(“loop starts now...n”); Now let’s move on to the second program. for(float f = 0.0; f < 20000000.0; f++) Since floating point arithmetic is not accurate, the ; // just loop over, do nothing operations can result in loss of precision and printf(“...done!”); rounding errors. In the loop, when the value of f } reaches 16777216.0, adding 1 doesn’t increment the value of f by 1, but gets rounded off. You can “Ah, easy...” you say! But let’s see the answers first. verify it with the following code segment: Program I fails with the assertion failure and Program II gets into an infinite loop after printing: float f = 16777216.0; assert(f == (f + 1)); “loop starts now...n”. This doesn’t fail with an assertion failure and works Before seeing the explanation, let’s have a quick fine! Now you know why it’s a bad idea to use floating point tutorial on floating point numbers. numbers in loops! The types that can represent the numbers with decimal points (where the position of the decimal point is not fixed, or in other words, is floating) are known as floating S.G. Ganesh is an engineer in Hewlett-Packard’s C++ point numbers. There is a standard available for specifying compiler team. He has authored a book “Deep C” (ISBN 81- 7656-501-6). He is also a member of the ANSI/ISO C++ the implementation of floating point numbers (The IEEE Standardisation committee (JTC1/SC22/WG21) 754 Floating Point Standard). Based on that, typically, C representing HP. You can reach him at compilers support float for representing single precision sgganesh@gmail.com. numbers and double type for representing the numbers www.linuxforu.com | LINUX FOR YOU | FEBRUARY 2007 119 CMYK