Hot answers tagged

93

You need to keep in mind that in FPU arithmetics, 0 doesn't necessarily has to mean exactly zero, but also value too small to be represented using given datatype, e.g. a = -1 / 1000000000000000000.0 a is too small to be represented correctly by float (32 bit), so it is "rounded" to -0. Now, let's say our computation continues: b = 1 / a Because a is ...


75

The CPU has built in detection. Most instruction set architectures specify that the CPU will trap to an exception handler for integer divide by zero (I don't think it cares if the dividend is zero). It is possible that the check for a zero divisor happens in parallel in hardware along with the attempt to do the division, however, the detection of the ...


75

Two common cases to consider: Integer arithmetic Obviously if you are using integer arithmetic (which truncates) you will get a different result. Here's a small example in C#: public static void TestIntegerArithmetic() { int newValue = 101; int oldValue = 10; int SOME_CONSTANT = 10; if(newValue / oldValue > SOME_CONSTANT) { ...


68

Although there were older precursors, the influential French mathematician Rene Descartes is usually credited for introducing superscripted exponents (ab) into mathematical writing, in his work Geometrie which was published in 1637. This is the notation still universally used in mathematics today. Fortran is the oldest programming language widely used for ...


65

Suppose we're designing a new language and we want Sqrt to be an instance method. So we look at the double class and begin designing. It obviously has no inputs (other than the instance) and returns a double. We write and test the code. Perfection. But taking the square root of an integer is valid, too, and we don't want to force everyone to convert to ...


54

TL;DR The key takeaway here is that there is a world of difference between the number 65535 and a piece of text which represents the digits '6', '5', '5', '3' and '5'. It may look the same to you when rendered on a computer screen, but to a computer internally, they are completely unrelated to one another. The rest of this answer is a lengthy elaboration on ...


47

According to MDN Math.min accepts only numbers, and if one of the arguments is not a number, it'll return NaN. That's not what it says (bold emphasis mine): If at least one of arguments cannot be converted to a number, the result is NaN. Type Conversion: Math.min uses ToNumber to convert its arguments. ToNumber uses ToPrimitive to convert Objects (and ...


46

Your argumentation against floating point numbers is very fragile, probably because of naivety. (No offense here, I find your question is actually very interesting, I hope my answer will also be.) A classic argument is that floats provide a greater range, but high precision integers can meet this challenge now. For example: with modern 64-bit ...


46

There isn't any, and it's pretty arbitrary. The only useful distinction is between first class, and all others. Every case that's in the "other" bracket has its own distinct set of rules in each case and lumping them all together just isn't very helpful. "First class" means "You don't have to look up the rules", essentially, and "other" is "You have to ...


38

This is not a C++ library issue but a question of mathematical terminology. In mathematics, a norm can mean different things: What you call norm is the Euclidian norm, which is the distance to the origin. In C++ it's abs(). This naming convention has the advantage of being consistent for complex and for real numbers (the origin in the latter case being ...


34

It depends on the language, on the compiler, on whether you are using integers or floating point numbers, and so on. For floating point number, most implementations use the IEEE 754 standard, where division by 0 is well defined. 0 / 0 gives a well defined result of NaN (not-a-number), and x / 0 for x ≠ 0 gives either +Infinity or -Infinity, depending on ...


26

Because switching to integers doesn't solve anything. The problem with floats isn't that they have inaccuracies, it's that half the people using them don't pay any attention to what's going on. Those same people aren't going to pay proper attention to the units they are using when they use an integer, and a different set of screw ups will happen. Repeat ...


25

Mathematical operations are often very performance-sensitive. Therefore, we will want to use static methods that can be fully resolved (and optimizied, or inlined) at compile time. Some languages do not offer any mechanism to specify statically dispatched methods. Furthermore, the object model of many languages has considerable memory overhead that is ...


25

I like your question as it potentially covers many ideas. On the whole, I suspect the answer is it depends, probably on the types involved and the possible range of values in your specific case. My initial instinct is to reflect on the style, ie. your new version is less clear to the reader of your code. I imagine I would have to think for a second or two (...


25

Christophe's post, whilst fully correct, does not actually answer the question why the terms look like they do. To give you definite answer for the reasons, you would have to ask someone from the C++ standard committee, but let me make an "educated guess": There was already a function name std::abs in use for the euclidean norm for float and double values,...


23

No. I'd probably call that premature optimization, in a broad sense, regardless of whether you're optimizing for performance, as the phrase generally refers to, or anything else that can be optimized, such as edge-count, lines of code, or even more broadly, things like "design." Implementing that sort of optimization as a standard operating procedure puts ...


22

This multiplication algorithm does not replace multiplication with addition. Instead, it splits the multiplication into a number of smaller multiplications that are easier for humans to understand. Humans (unlike computers) deal well with patterns and symbols, less so with large numbers (where “large“ means “multiple digits”). 321 × 254 × | 2E2 + 5E1 + ...


21

Physical characteristics of the universe (like the number of atoms in it) are not useful to determine the boundaries of number sizes, because useful calculations exist using numbers having wider ranges. Floating point numbers are a tradeoff between accuracy and range. They deliberately give up some accuracy to achieve greater range.


21

It is entirely a choice of language design. It also depends on the underlying implementation of primitive types, and performance considerations due to that. .NET has just one static Math.Sqrt method that acts on a double and returns a double. Anything else you pass to it must be cast or promoted to a double. double sqrt2 = Math.Sqrt(2d); On the other hand,...


19

Computers are not Turing Machines. They are Deterministic Finite State Machines. Turing Machines have infinite memory, computers have finite memory. Turing Machines have arbitrarily many (though finite) states, computers can't have arbitrarily many states, the number of different states that a computer can be in is bounded by its memory (a computer with 1&...


17

Why do we implement Fibonacci numbers naively using its definition instead of using the explicit formula https://brilliant.org/discussions/thread/the-explicit-formula-for-fibonacci-sequence/. We don't. No programmer ever computes Fibonacci numbers. Not recursively. Not iteratively. Not with Binet's Formula. (Yes, I know. There are a small number of ...


15

I would be motivated by the fact that there's a ton of special-purpose math functions, and rather than populate every math type with all (or a random subset) of those functions you put them in a utility class. Otherwise, you'd either pollute your auto-completion tooltip, or you'd force people to always look in two places. (Is sin important enough to be a ...


15

Of course, the pigeonhole principle states that colisions are inevitable for hashing algorithms. The point of hashing algorithms is not to prevent colisions. But to make intentional collisions difficult. An hashing algorithms becomes considered insecure when it becomes feasible to generate piece of data that results in specific hash. Or to extend piece of ...


14

You could define local functions that call the global static functions. Hopefully the compiler will inline the wrappers, and then the JIT compiler will produce tight assembly code for the actual operations. For example: class MathHeavy { private double sin(double x) { return Math.sin(x); } private double cos(double x) { return Math.cos(x); } ...


13

Because most of the processors that you use in your day to day life are not modern day 64 bit processors with crazy fast integer calculations or an over abundance of space. Most of your processors are 8-16 bit devices which run things like your car, microwave, or watch. Besides, what happens when you need to talk about a half of a unit, like a half of a ...


13

Unsurprisingly, you are indeed "doomed from the start". This "Japanese Multiplication" (which is a visual form of the grid method tought in UK primary schools since the 1990s) has a time complexity of at least O(n^2) where n is the number of digits in the numbers you are multiplying. This is because the number of intersections will be n*n, and you have to ...


13

Seems like you're wondering what would happen if someone made a CPU that doesn't explicitly check for zero before dividing. What would happen depends entirely on the implementation of the division. Without going into details, one kind of implementation would produce a result that has all bits set, e.g. 65535 on a 16-bit CPU. Another might hang up.


13

Use whichever one is less buggy and makes more logical sense. Usually, division by a variable is a bad idea anyway, since usually, the divisor can be zero. Division by a constant is usually just dependent on what the logical meaning is. Here's some examples to show it depends on the situation: Division good: if ((ptr2 - ptr1) >= n / 3) // good: check ...


Only top voted, non community-wiki answers of a minimum length are eligible