Re: When to use float (in teaching)
Christian wrote:
Stefan Ram schrieb:
I teach some properties of the data type ?double?:
public class Main
{ public static void main( final java.lang.String[] args )
{ java.lang.System.out.println( 0.1 + 0.1 + 0.1 == 0.3 );
java.lang.System.out.println( 1.1 * 1.1 == 1.21 ); }}
false
false
. I also teach that beginners should not use the data type
?float?, because it will only cause trouble.
imho this is a bad thing to tell...
Its like telling "Don't use int because it will only give you trouble
, always use long"
This is a false comparison. Short, int and long all have identical accuracy, the
only difference is in their range. If the data you need to process can be held
in an int you might as well use an int, there is nothing whatever to be gained
by using long. This is most definitely not the case when dealing with floating
point numbers.
For most applications (as in 99% of all I see) float is more than enough
for floating point computations.
But why use float at all? Unless there is a compelling reason to do so (speed,
memory limitations) why not just use double as the default? There is no good
reason not to. Starting off by learning to use float gets you into the habit of
using float and may have serious repercussions at some later date.
And as one usually uses int and it
doesn't matter if you use long instead ... in some applications you are
just better off with using int or short or byte where applicable ...
There are 2 situations where double really starts to be useful ...
1. very high numbers ... and you don't want to use BigInt and co...
Or very small numbers
2. high numbers that need high precicision ... if the number is in the
Billions and you still need precicion behind the comma ...
any number that requires higher precision, it's not a function of the magnitude
unless it exceeds the exponent limits of float.
2. sometimes happens i.e. if very large numbers are multiplied with very
small ones.. like a * a^-1
1. is rather rare...
or when calculating the difference between a large and small number etc.
In fact, you might as well just use double everywhere, and only use float when
it's required...
--
Nigel Wade