Moving decimal places over in a double

If you use double or float, you should use rounding or expect to see some rounding errors. If you can’t do this, use BigDecimal. The problem you have is that 0.1 is not an exact representation, and by performing the calculation twice, you are compounding that error. However, 100 can be represented accurately, so try: … Read more

Random weighted selection in Java

I would use a NavigableMap public class RandomCollection<E> { private final NavigableMap<Double, E> map = new TreeMap<Double, E>(); private final Random random; private double total = 0; public RandomCollection() { this(new Random()); } public RandomCollection(Random random) { this.random = random; } public RandomCollection<E> add(double weight, E result) { if (weight <= 0) return this; total … Read more

Comparing double values in C#

It’s a standard problem due to how the computer stores floating point values. Search here for “floating point problem” and you’ll find tons of information. In short – a float/double can’t store 0.1 precisely. It will always be a little off. You can try using the decimal type which stores numbers in decimal notation. Thus … Read more

When should I use double instead of decimal?

I think you’ve summarised the advantages quite well. You are however missing one point. The decimal type is only more accurate at representing base 10 numbers (e.g. those used in currency/financial calculations). In general, the double type is going to offer at least as great precision (someone correct me if I’m wrong) and definitely greater … Read more

Checking if a double (or float) is NaN in C++

First solution: if you are using C++11 Since this was asked there were a bit of new developments: it is important to know that std::isnan() is part of C++11 Synopsis Defined in header <cmath> bool isnan( float arg ); (since C++11) bool isnan( double arg ); (since C++11) bool isnan( long double arg ); (since … Read more

tech