SlideShare uma empresa Scribd logo
1 de 1
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

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
웅식 전
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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)
 

Mais de Ganesh Samarthyam

Mais 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
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

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