Hacker News new | past | comments | ask | show | jobs | submit login

Rationals are computationally nasty. Even if you have hardware acceleration, they are going to be slow. Here's why:

An integer addition (or subtraction) can be done in 1 clock cycle; multiplies will take 3; and division takes far longer, think 20 cycles or more. Fixed point additions are the same as integer additions, while multiplies and divisions both take a multiply and a division (although you can convert one of them to a shift if it's binary fixed point).

Floating point additions are more expensive than integers (due to the need of normalization), taking about 3 cycles. But multiplies also take about that amount of time, and you can do a fused multiply and add in the same amount of time, 3-4 cycles. Divisions, like integers, are more painful, but they're actually faster than integer division: a floating point division is going to be closer to 10 cycles, since you have less precision to worry about.

For rational arithmetic, you essentially have to run a GCD algorithm to do the normalization steps. Even if this were implemented with special hardware, it would be on the same order as an integer division operation in terms of latency. An addition or subtraction would cost a GCD, 4 multiplies, and an addition, while multiplication and division are cheaper at a GCD and two multiplications each.

In summary, if you're looking at the cost of doing a dot product, it's 4 cycles per element if integer or floating-point; 5-25-ish if fixed; and 50+ for rational (assuming hardware acceleration; pure software is an order of magnitude slower). It's telling that the recommendation for solving rational equations is to either convert to integers and do integer linear programming, or to do a floating-point approximation first and then refine in the rational domain.

A final note is that integer division is much more rarely vectorized than floating-point division, so fixed and rational arithmetic are not going to see benefits from vectorization on current hardware.




> Rationals are computationally nasty. Even if you have hardware acceleration, they are going to be slow

So what? If you have both rationals and floats (and maybe arbitrary-precision decimals in between) as first class citizens, and give literals the most natural exact type unless a modifier to select floats is used, there's no unnecessary footguns.


What is nasty; brittle ad hoc code that tries to bend binary floats and or integer types to do the work rationals.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: