Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is meant by Real Numbers or values in java and a very elementary explanation of primitive types in java

Tags:

java

primitive

A quote from a book on Java "I advise sticking to type double for real numbers" and also "you should stick to the double type for real values". I don't understand what is meant by a real number or value... Real number as opposed to what?

like image 841
user1732538 Avatar asked Oct 09 '12 18:10

user1732538


Video Answer


2 Answers

Real number as opposed to integers. In mathematics, a real number can be any value along the continuum, such as 4.2 or pi. The integers are a subset of the real numbers.

Here are the Java primitives. Some of the important ones for numbers include int when you want a whole number and double when you want to allow fractions. If you deviate from those, you generally have a specific reason for doing so.

Integers are very easy to represent in binary, and it's easy to specify a specific range of integers that can be represented exactly with a specified number of bits. An int in Java uses 32 bits and gets you from -2,147,483,648 to 2,147,483,647. The other integral types are similar but with varying numbers of bits.

However, representing numbers along the continuum is more difficult. Between any two points on the real number line, there are infinitely many other real numbers. As such, it's not possible to exactly represent all of the real numbers in an interval. One way around this is with floating-point numbers. I won't get too much into the details, but basically some precision is lost so that there are gaps in what can be represented exactly. For many purposes this is inconsequential, but for things like tracking a bank account balance, this can matter. It might be worth reading the famous What Every Computer Scientist Should Know About Floating-Point Arithmetic.

In Java, one way around some of these issues includes using something like BigDecimal. Some other languages might offer other primitives as alternatives. For instance, C# has a decimal data type while Java does not.

like image 123
Michael McGowan Avatar answered Nov 08 '22 17:11

Michael McGowan


Real means floating point, i.e. double or float, as opposed to integral (int or long)

like image 37
Richard Close Avatar answered Nov 08 '22 18:11

Richard Close