Why doesn’t Java throw an Exception when dividing by 0.0?

Java’s float and double types, like pretty much any other language out there (and pretty much any hardware FP unit), implement the IEEE 754 standard for floating point math, which mandates division by zero to return a special “infinity” value. Throwing an exception would actually violate that standard. Integer arithmetic (implemented as two’s complement representation … Read more

How to compare double numbers?

There is no general solution for comparing floating-point numbers that contain errors from previous operations. The code that must be used is application-specific. So, to get a proper answer, you must describe your situation more specifically. For example, if you are sorting numbers in a list or other data structure, you should not use any … Read more

How do I convert a double into a string in C++?

// The C way: char buffer[32]; snprintf(buffer, sizeof(buffer), “%g”, myDoubleVar); // The C++03 way: std::ostringstream sstream; sstream << myDoubleVar; std::string varAsString = sstream.str(); // The C++11 way: std::string varAsString = std::to_string(myDoubleVar); // The boost way: std::string varAsString = boost::lexical_cast<std::string>(myDoubleVar);

How To Represent 0.1 In Floating Point Arithmetic And Decimal

I’ve always pointed people towards Harald Schmidt’s online converter, along with the Wikipedia IEEE754-1985 article with its nice pictures. For those two specific values, you get (for 0.1): s eeeeeeee mmmmmmmmmmmmmmmmmmmmmmm 1/n 0 01111011 10011001100110011001101 | || || || || || +- 8388608 | || || || || |+— 2097152 | || || || || … Read more

Why does Math.round(0.49999999999999994) return 1?

Summary In Java 6 (and presumably earlier), round(x) is implemented as floor(x+0.5).1 This is a specification bug, for precisely this one pathological case.2 Java 7 no longer mandates this broken implementation.3 The problem 0.5+0.49999999999999994 is exactly 1 in double precision: static void print(double d) { System.out.printf(“%016x\n”, Double.doubleToLongBits(d)); } public static void main(String args[]) { double … Read more

Swift double to string

It is not casting, it is creating a string from a value with a format. let a: Double = 1.5 let b: String = String(format: “%f”, a) print(“b: \(b)”) // b: 1.500000 With a different format: let c: String = String(format: “%.1f”, a) print(“c: \(c)”) // c: 1.5 You can also omit the format property … Read more

Convert float to double without losing precision

It’s not that you’re actually getting extra precision – it’s that the float didn’t accurately represent the number you were aiming for originally. The double is representing the original float accurately; toString is showing the “extra” data which was already present. For example (and these numbers aren’t right, I’m just making things up) suppose you … Read more

tech