Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected behavior of Int#/ on zero division #9707

Closed
snacks02 opened this issue Aug 28, 2020 · 5 comments
Closed

Unexpected behavior of Int#/ on zero division #9707

snacks02 opened this issue Aug 28, 2020 · 5 comments

Comments

@snacks02
Copy link
Contributor

Int#/ and Int#// produce different output when divided by zero:

1 / 0 # => Infinity
1 // 0 # => Unhandled exception: Division by 0 (DivisionByZeroError)

crystal --version:

Crystal 1.0.0-dev [b2b4a8bdc] (2020-08-24)

LLVM: 10.0.1
Default target: x86_64-pc-linux-gnu
@asterite
Copy link
Member

That's expected. Check out Ruby (or any language for that matter):

irb
irb(main):001:0> 1 / 0
Traceback (most recent call last):
        5: from /Users/asterite/.rbenv/versions/2.6.6/bin/irb:23:in `<main>'
        4: from /Users/asterite/.rbenv/versions/2.6.6/bin/irb:23:in `load'
        3: from /Users/asterite/.rbenv/versions/2.6.6/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
        2: from (irb):1
        1: from (irb):1:in `/'
ZeroDivisionError (divided by 0)
irb(main):002:0> 1.fdiv(0)
=> Infinity

In Ruby, / between integers is like our //. And fdiv is like our /.

@snacks02
Copy link
Contributor Author

snacks02 commented Aug 28, 2020

You are right. There are even specs for that.

Although, it is my fault that I did not check it before, Python, Golang and probably other languages raise an exception on both cases:

Python:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(1.0 / 0.0)
ZeroDivisionError: float division by zero

Shouldn't Crystal do the same?

@asterite
Copy link
Member

I don't know

@bcardiff
Copy link
Member

I don't think so. Infinity and NaN are valid values of float.

@snacks02
Copy link
Contributor Author

They are valid, but I would say it's rather confusing.

I don't see any cases (apart from following standards, which, despite everything, some languages break) where Infinity would make more sense than an exception. On the other hand, I can imagine situations where throwing an exception would result in cleaner and more consistent code.

I do not insist on my position, but the current behavior seems a bit wrong to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants