- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Floating point operators and associativity in Java
Following programs shows the float arithmetic can cause dubious result if integer values are used using float variables.
Example
public class Tester { public static void main(String[] args) { float a = 500000000; float b = -500000000; float c = 1; float sumabc1 = a+(b+c); float sumabc2 =(a+b)+c; System.out.println("Floating Point Arithmetic"); System.out.println("a + ( b + c ) : " + sumabc1); System.out.println("(a + b) + c : " + sumabc2); float sumbc = b + c; float sumab = a + b; System.out.println("b + c : " + sumbc); System.out.println("a + b : " + sumab); int a1 = 500000000; int b1 = -500000000; int c1 = 1; int sumabc11 = a1+(b1+c1); int sumabc21 =(a1+b1)+c1; System.out.println("Integer Arithmetic"); System.out.println("a + ( b + c ) : " + sumabc11); System.out.println("(a + b) + c : " + sumabc21); int sumbc1 = b1 + c1; int sumab1 = a1 + b1; System.out.println("b + c : " + sumbc1); System.out.println("a + b : " + sumab1); } }
Output
Floating Point Arithmetic a + ( b + c ) : 0.0 (a + b) + c : 1.0 b + c : -5.0E8 a + b : 0.0 Integer Arithmetic a + ( b + c ) : 1 (a + b) + c : 1 b + c : -499999999 a + b : 0
Here you can see that a + ( b + c ) is not same as (a + b) + c in float arithmetic.
The reason behind the same is the rounding off of the result because of floating point arithmetic. b + c results in -500000000 instead of -499999999 whereas the same in integer arithmetic yield the desired result.
- Related Articles
- Floating Point Operations and Associativity in C, C++ and Java
- C++ Operators with Precedence and Associativity
- Floating-point hexadecimal in Java
- Format floating point number in Java
- Floating-point conversion characters in Java
- Format floating point with Java MessageFormat
- Fixed Point and Floating Point Number Representations
- Decimal fixed point and floating point arithmetic in Python
- Apply modulus operator to floating-point values in Java
- What is the difference between integer and floating point literals in Java?
- Java program to multiply given floating point numbers
- Java Program to Multiply Two Floating-Point Numbers
- Floating point comparison in C++
- C++ Floating Point Manipulation
- Signed floating point numbers

Advertisements