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?
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.
Real means floating point, i.e. double
or float
, as opposed to integral (int
or long
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With