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

> Almost every popular language launches an exception when you do a divide by zero.

1.) Divide by zero returns Inf, not NaN.

2.) I just tried C++, Java, C#, Go[1], and the champion of safety: Rust. All of them evaluate to Infinity when dividing a double by 0.0. No exceptions to be found.

> Try it, I'd like to see the results. I'm not too familiar with the processor implementation, but something tells me that if every system level language implements exceptions for division by zero then the cost must be minimal.

But they don't. Not every system level language even has exceptions and the ones that do return Inf as stated above.

> At most it's just one instruction.

Branches can be expensive if the branch predictor chooses the wrong path and forces a pipeline flush. Should be able to work with the predictor so that happy paths are true and that should make it less likely, but I'm not an expert there.

> The only place a division by zero operation can legally occur is if the zero arrives via IO. In that case it's better to sanitize the input or detect the zero rather than catch an exception.

In many applications this is true. Not all.

[1]: You do need to make sure Go treats both operands as doubles, easiest way to be sure is to declare x and y as float64 and then divide them afterward. But when actually dividing a float64 by another float64, it does evaluate to Inf as well.




> All of them evaluate to Infinity when dividing a double by 0.0. No exceptions to be found.

Well, Rust doesn't have exceptions, so it wouldn't happen, but yeah. To your parent, these languages follow IEEE 754, as far as I know, which specifies this behavior.


Go throws an exception with 1.0/0.0. Unless you specify the type as float64.

Ok overall I'm wrong.

But either way poor design from a usability standpoint and from a consistency standpoint because ints don't do this.


Yeah, floats and ints are just fundamentally different, especially when you're at the level of caring about how hardware deals with things.

TIL about Go:

Numeric constants represent exact values of arbitrary precision and do not overflow. Consequently, there are no constants denoting the IEEE-754 negative zero, infinity, and not-a-number values.

https://golang.org/ref/spec


Yeah that's one of those things that I learn, and then forget, and then relearn, and forget...

Would probably retain it better if I used Go as my primary language for a year or two.




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

Search: