I was wondering if any of you java geeks could help me with the following:
package testproject;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
doubleClass l = new doubleClass();
while(true)
{
l.countUp();
System.out.println(l.getNumber());
Scanner in = new Scanner(System.in);
// wait for <Enter> to be pressed
in.nextLine();
}
}
}
package testproject;
public class doubleClass {
private double number;
public doubleClass()
{
number = 0;
}
public void countUp()
{
number += 0.01;
}
public double getNumber()
{
return number;
}
}
So basically a very simple program to test a double.
The problem is that the number fucks up at some points.
e.g. instead of printing 0.06 it prints 0.060000000000000005
Why the fuck is this and how can I get it to work normally
like in c or c++?
you cant represent every number so floating point gives an aproximation. Maybe java uses diferent exponent or fraction lenght than c++ in his representation.
anyways,c++ doesnt do it flawlessly, on my box prints
0.000000000000000
0.009999999776483
0.019999999552965
0.029999999329448
0.039999999105930
0.050000000745058
0.060000002384186
0.070000000298023
You're using Java................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
Name:
Anonymous2008-02-14 11:48
I'm sorry, but we only program in C# around these parts. VB.NET is also acceptable.
I'd ask you to look up roundoff errors and out.format, but you wouldn't understand it anyway.
Name:
Anonymous2008-02-14 12:17
I'm sorry, but we only program in Lisp around these parts. Haskell is also acceptable.
I'd ask you to look up monads and higher-order functions, but you wouldn't understand it anyway.
Name:
Anonymous2008-02-15 16:18
Use BigDecimals if you want to do stuff like that.
Or use rational numbers.
Or use a computer that operates in base 10.
Anyway, you could read some papers on floating point
Name:
Anonymous2008-02-15 17:09
Or use a computer that operates in base 10.
Too bad the JVM can't.
Name:
Anonymous2008-02-15 19:06
BCD FTW
Name:
Anonymous2009-03-06 11:47
Using one to type this is a liar and a community in denial about my assassination of the Sussman of the relationship between dqn voltages.