Slashdot Mirror


Ask Slashdot: What's the Harm In a Default Setting For Div By Zero?

New submitter CodeInspired writes: After 20 years of programming, I've decided I'm tired of checking for div by zero. Would there be any serious harm in allowing a system wide setting that said div by zero simply equals zero? Maybe it exists already, not sure. But I run into it all the time in every language I've worked with. Does anyone want their div by zero errors to result in anything other than zero?

109 of 1,067 comments (clear)

  1. Yes by Fwipp · · Score: 5, Insightful

    Does anyone want their div by zero errors to result in anything other than zero?

    Yes.

    1. Re:Yes by Venerable+Vegetable · · Score: 3, Insightful

      Right, I don't even... ehh... totally confused. It's not aprils fools right? Did this article get approved just to mock the submitter, or has Slashdot gone totally of the rails? Ok don't answer that last question.

      Maybe the submitter would care to submit an example of where he thinks it would be appropriate to equal divide by zero to zero, because I honestly don't know where to start.

    2. Re:Yes by Darinbob · · Score: 2

      This sounds so much like a beginning programmer question. Sorts of things I used to hear when being a teaching assistant. Too much effort, can this be simpler?

      Now in some cases, people may not care. There are a lot of cases where one ignores errors in real life. But lots of programmers love to crash at a moment's notice: sprinkle the code liberally with asserts rather than try to recover, let main() catch all errors and then print an error and exit, etc. However if you're ignoring an error you should abort the operation you were doing in a way that lets you continue gracefully.

      That means don't treat a divide-by-zero as zero ever, it means treat divide-by-zero as a notification that you should abort the operation you were doing. Continuing after a divide-by-zero error is just as bad as crashing. Throw away the answer rather than continue, otherwise it implies that the result of the calculation was irrelevant.

      One language I thought was interesting was "Icon", where the type of a result could be "failure", and any operation on failure results in another failure.

      Anyway, if someone wants to ignore divide-by-zero and to treat it as zero result, then they need a GOOD reason for it. And "it's tedious to check" is not at all a good reason.

    3. Re:Yes by ndrw · · Score: 2

      Then they can get the fuck off this web site. We don't need it to be everything to everyone. We need it to be news for nerds, stuff that matters. Nerds, by definition know something about programming and hopefully more about math.

    4. Re:Yes by AthanasiusKircher · · Score: 5, Funny

      Right, I don't even... ehh... totally confused. It's not aprils fools right? Did this article get approved just to mock the submitter, or has Slashdot gone totally of the rails?

      Well, Slashdot recently implemented a new engine for approving articles, but there was a place in the code where one could end up dividing by zero, and they just decided to arbitrarily set that value to "post a random nonsensical Ask Slashdot question."

      So, Timothy screwed something up... and, well, rather than throwing up an exception -- VOILA... this story was approved!

      I'm surprised you haven't noticed this before -- I think it's how most "Ask Slashdot" questions get posted these days.

  2. Simple by Anonymous Coward · · Score: 5, Insightful

    It means your code is wrong. Who knows what led up to that /0 error.

  3. Bugs? by weilawei · · Score: 4, Informative

    Burning karma here to see if anyone else has the same problem. Mod offtopic if you like.

    New posts of mine aren't showing up for about half an hour typically. Do they need to be staff approved now or something?

    Second, on several front page stories, I no longer have the option to post. They say, "Nothing to see here. Move along" and "Archived discussion".

    I think the new design changes are pretty alright, but those two are breaking changes for me.

    1. Re:Bugs? by blue+trane · · Score: 4, Informative

      Titles are now partially obscured by the comment count and the classification icons. Screenshot: http://snag.gy/ciB02.jpg

    2. Re:Bugs? by aardvarkjoe · · Score: 4, Funny

      Didn't you hear? Slashdot is trying this cutting-edge "Agile Development" thing. The idea is that instead of testing your changes, you just make them directly on your production site and see what happens. It's the wave of the future!

      --

      How can we continue to believe in a just universe and freedom to eat crackers if we have no ale?
    3. Re:Bugs? by damn_registrars · · Score: 2

      The idea is that instead of testing your changes, you just make them directly on your production site and see what happens

      Does that mean that slashdot is extremely cutting edge? They've been doing this for years!

      --
      Damn_registrars has no butt-hole. Damn_registrars has no use for a butt-hole.
    4. Re:Bugs? by Anonymous Coward · · Score: 5, Insightful

      You think *you're* having problems. I'm seeing actual stories with titles like "Ask Slashdot: What's the Harm In a Default Setting For Div By Zero?"

    5. Re:Bugs? by techno-vampire · · Score: 2

      I had the same experience. However, I've also found that clicking on the number of comments will get you to the discussion. I do wish that the webmonkies would give the crack-pipes back to the mods and stop uglifying the site.

      --
      Good, inexpensive web hosting
    6. Re:Bugs? by PopeRatzo · · Score: 2

      New posts of mine aren't showing up for about half an hour typically. Do they need to be staff approved now or something?

      Second, on several front page stories, I no longer have the option to post. They say, "Nothing to see here. Move along" and "Archived discussion".

      Slashdot functionality is like a guy who goes to a massage parlor.

      It comes and goes.

      --
      You are welcome on my lawn.
  4. WTF is this shit? by Anonymous Coward · · Score: 3, Insightful

    Umm, wtf is this shit?

    1. Re:WTF is this shit? by __aaclcg7560 · · Score: 2

      A divide by zero error. Happens all the time.

  5. Sounds like a plan! by Whip · · Score: 5, Insightful

    "Rather than failing when an unexpected condition arises, I want all software on my system to continue running with a possibly invalid or meaningless internal state."

    Sure, what could go wrong?

    1. Re:Sounds like a plan! by Anonymous Coward · · Score: 4, Informative

      I won't mention names to hopefully dodge any lawyers lurking about, but "a friend" works in the airline industry and a certain commercial aircraft flight computer on receiving bad or missing data from the Inertial Reference System would happily go on reporting a value without indicating an error. Luckily, this friend became aware of the problem trying to resolve a CG issue before takeoff. Fun times.

    2. Re:Sounds like a plan! by Dunbal · · Score: 3, Insightful

      Yeah but for some people "if(investors >= 1)" is hard.

      --
      Seven puppies were harmed during the making of this post.
  6. And how do you know if there's an error then? by CSG_SurferDude · · Score: 5, Insightful

    So how do you know if you had an error if you return "0" for a divide by 0 error? Now you have a whole 'nother set of problems to code around.

  7. I want my division by zero errors to be errors by Lumpio- · · Score: 5, Insightful

    Because that usually means I'm trying to do something that's mathematically meaningless and I'd rather handle the special case than silently get a meaningless result.

    1. Re:I want my division by zero errors to be errors by TopherC · · Score: 4, Interesting

      I agree here. One easy example is computing an average: add up the numbers and divide by N. What if you have no numbers to average and N == 0? That doesn't mean the average is zero, it means you don't have an average. You always have to check for /0 errors, not because you want to keep the program from crashing but because you need to handle all the special cases. It's usually (not always) better to crash to alert you to an un-handled condition than to pretend nothing is wrong.

      Should all null pointer exceptions or segfaults be handled quietly in some arbitrary way, in order to make software more "robust?"

    2. Re:I want my division by zero errors to be errors by Chris+Mattern · · Score: 2

      Well in Java, integer div by zero causes an ArithmeticException, whereas div by a floating-point zero results in +/-Infinity but no exception. Why should only integer code generate exceptions and not floating point code? Do floating point errors not matter?

      Because while 0/0 is undefined and an error everywhere, 1/0 is indeed infinity. Floating point has a representation for infinity, so you get that back. Integer types have no representation for infinity, so you get back an error instead. INT_MAX and INT_MIN are not infinity and would be dangerous incorrect to treat them as such, no matter how large their magnitude.

  8. Well... by TaleSpinner · · Score: 4, Interesting

    ...aside from the fact that it's completely wrong I can't see a problem with it.

  9. Infinity by Anonymous Coward · · Score: 5, Insightful

    I think infinity makes a bit more sense than zero. And max is the closest thing to infinity.

    1. Re:Infinity by joeblog · · Score: 4, Informative

      When you have 0/0, you hit two "obvious" but contradictory rules in basic algebra:

      Rule one: anything multiplied by zero is zero
      Rule two: anything divided by itself is one

      Mathematicians don't know which rule has precedence for 0/0, so there's no way a dumb machine can figure it out, which is why most programing languages just throw an exception if zero is the denominator.

      --
      If it works, it's obsolete
    2. Re:Infinity by dissy · · Score: 4, Interesting

      When you have 0/0, you hit two "obvious" but contradictory rules in basic algebra:

      Rule one: anything multiplied by zero is zero
      Rule two: anything divided by itself is one

      But divide by zero isn't covered by either of those two rules of algebra.

      Asking what is X divided by zero is no different than asking what is Y plus red, or what is Z times pineapple.

      I say focus on a proper mathematical answer for multiplying by blue first, and then apply it to the equally nonsensical divide by zero question.

    3. Re:Infinity by lenart · · Score: 5, Informative

      Mathematically, the result is undefined. So neither is correct. Nor is anything inbetween.

    4. Re:Infinity by spitzak · · Score: 3, Informative

      Actually IEEE floating point has a signed zero (+0 and -0 are different values) to solve exactly that. If x is positive, x/+0 is +infinity, x/-0 is -infinity. 0/0 (with any type of 0) returns NaN.

      However I believe the article was talking about *integer* division by zero, not floating point.

    5. Re:Infinity by joeblog · · Score: 3, Informative

      Let me rewrite that as:

      Rule 1: 0*X (where X = 1/0)
      Rule 2: X/X (where X = 0)

      I've had this argument often with APL fans who don't get that as obvious as 0/0 = 1 may sound, it's not mathematically sound.

      --
      If it works, it's obsolete
    6. Re:Infinity by Verdatum · · Score: 2
      it approaches infinity if you start at one and get closer and closer and closer to 0. N/.00000001 is pretty high.

      But it approaches negative infinity if you start at -1 and get closer and closer and closer to 0. N/-.00000000001 is pretty low.

      because of this discontinuity...the largest discontinuity possible in fact, the actual value of N/0 cannot be any of these compromises. It has to not exist.

    7. Re:Infinity by Samantha+Wright · · Score: 4, Insightful

      More importantly is what happens when you graph it: the limit of 1/x as x approaches zero is discontiguous. It's positive infinity when descending on the positive numbers, but negative infinity when ascending from the negatives. No one value can represent both!

      --
      Bio questions? Ask me to start a Q&A journal. Computer analogies available for most topics!
    8. Re:Infinity by khallow · · Score: 5, Insightful

      Mathematicians don't know which rule has precedence for 0/0

      No, mathematicians known that there is no consistent number which would be an answer for 0/0. For example, take any number r and consider the fraction (rx)/x. For x not zero, it evaluates to r. Set x to zero and there's an argument that 0/0 should be r. But r wasn't special so you have an arbitrary argument with no special value of r indicated as the natural value of 0/0.

      Similarly, if you consider the fraction x/(x^2), you get an argument that 0/0 should be infinite (plus or negative depending on whether you approach zero from the positive side or negative). In other words, 0/0 is indeterminate with the value, if any, depending on how you approach 0/0.

    9. Re:Infinity by ShanghaiBill · · Score: 4, Insightful

      Mathematicians don't know which rule has precedence for 0/0

      In many situations, you can use L'Hopital's Rule to resolve 0/0. But a properly written program should never get in a situation of dividing by zero, and this is one of the dumbest "Ask Slashdot" questions in a while. Masking the interrupt makes about as much sense as driving blindfolded so you don't see the people you are running over.

    10. Re:Infinity by khallow · · Score: 5, Insightful

      How about evaluating 0/(0*0) versus (0/0)/0? Assuming 0/0=1 gives you inconsistent outcomes unless you're willing to sacrifice associativity of multiplication and division.

    11. Re:Infinity by rwa2 · · Score: 4, Informative

      When you have 0/0, you hit two "obvious" but contradictory rules in basic algebra:

      Rule one: anything multiplied by zero is zero
      Rule two: anything divided by itself is one

      Mathematicians don't know which rule has precedence for 0/0, so there's no way a dumb machine can figure it out, which is why most programing languages just throw an exception if zero is the denominator.

      It's mathematically possible to do some form of 0/0 using limits and the calculus.

      lim x->0 x/x = 1

      Also lets you do some interesting other things, like:

      lim x->0 x^2/x = 2
      lim x->0 sin(x) / x = 1

      Shouldn't be too hard to get a function that gives you the correct "approximate" value of the function near the indeterminate point, if there is one. It's just a bunch of special cases that you have to check for every time you do an operation that might possibly result in a div/0 error, right? Go ahead. DO IT! I'll wait.

    12. Re:Infinity by ThePhilips · · Score: 2, Informative

      Asking what is X divided by zero is no different than asking what is Y plus red, or what is Z times pineapple.

      Actually these do make more sense.

      Ah, you naive physicists. Your attempts at trying to attach the math to reality always make me smile. And your believe that the human words mean the same thing in math - that's just hilarious.

      Because, it is just math. It's human invention and we can do whatever we like with it.

      But to the point: division by zero is not illegal - it is simply not defined.

      The usual mathematical workaround is to simply define another operation - "zivition" or whatever you like - which is just like division, but in case of X/0, it has value of X or 1 or 0 or whatever you like. Or one can even go step further and define the zivition as ternary operation: ziv(X, Y, Z) = { div(X,Y), Y!=0; Z, Y==0 }

      --
      All hope abandon ye who enter here.
    13. Re:Infinity by AmiMoJo · · Score: 2

      This. If the OP is tired of checking for this condition, they are doing it wrong. It's not hard to write code where there is simply no possibly of a division by zero happening.

      Even when handling external input you need to validate it in almost every case, so adding a simple !=0 test is trivial and a minor part of the bigger problem.

      --
      const int one = 65536; (Silvermoon, Texture.cs)
      SJW, n: "Someone I don't like, and by the way I'm a fuckwit" - AC
    14. Re:Infinity by ShanghaiBill · · Score: 2

      That's something entirely different.

      No, it isn't different. If you are about to calculate x/y, and both x and y are zero, then you may be able to look at where x and y came from. If both of them were calculated from differentiable functions, then L'Hopital's Rule may help you evaluate the ratio.

    15. Re:Infinity by onepoint · · Score: 2

      While I will respect the idea the you think this is the dumbest question in a while, It's does show what people are feeling and being frustrated by. And what I have found great about Slashdot is some of the more creative reply's. I am looking forward to this.

      Personally, I think, clean code with check's and filters makes for better programs, but today's behavior seems to indicate that product needs to be out the door ASAP or you are out the door ASAP. so sloppy code consistently comes forth.

      --
      if you see me, smile and say hello.
    16. Re:Infinity by Wycliffe · · Score: 2

      I think infinity makes a bit more sense than zero. And max is the closest thing to infinity.

      I think the biggest problem is that depending on the application, you might want different things to happen.
      I find in my code, that I tend to want one of 4 mutually exclusive things to happen:
      1) If denominator is zero, die.
      2) If denominator is zero, set denominator to 1 and continue.
      3) If denominator is zero, set denominator to 0.0001 (or some other similiar small number) and continue.
      4) If denominator is zero, set final result of x/0 to zero.

      Honestly, in my experience #4 (which is what the original poster suggested everyone should want) is rarely
      what I want. I almost always want one of the first 3. I do occasionally want #4 but setting the final result
      to zero just happens to not be the use cases that I personally run into the most.

    17. Re:Infinity by vux984 · · Score: 5, Informative

      When you have 0/0, you hit two "obvious" but contradictory rules in basic algebra:

      Rule one: anything multiplied by zero is zero
      Rule two: anything divided by itself is one

      Ugh no, just no.
      "Rule one: anything multiplied by zero is zero"

      Yes, this is called, amongst other things, the zero property of multiplication. However 0/0 is not a multiplication and the rule is not relevant, and there is no conflict.

      Secondly your "rule two" is not actually rule of algebra. There is no rule x/x = 1.

      There is an identity rule for division: anything divided by one is itself (x/1 = x) but there is no rule that says x/x = 1

      You can derive "rule two" from the identity rule for multiplication x*1 = x --> x/x = 1

      However, that transformation always stipulates that x 0 because division by zero is undefined.

      Mathematicians have no issue determine which rule has precedence, because neither rule applies to 0/0.
      There is no conflict. Division by zero is specifically "undefined".

      Consider the equation; x/x.

      http://www.wolframalpha.com/in...

      The graph of the function is a horizontal line at y=1, with a discontinuity at 0. (if x=0, x/x=0/0) So 0/0 should be 1 right? Because everywhere else on the graph x/x = 1??

      http://www.wolframalpha.com/in...

      Now consider the equation 2x/x.

      http://www.wolframalpha.com/in...

      As x approaches 0 (lim x->0) from either the left or right the limit of the equation is 2. A graph of the function is horizontal line at y=2, with a discontinuity at 0. But every where else 2x/x = 2. So shouldn't 2(0)/0 = 0/0 = 2? So 0/0 should be 2 right?

      http://www.wolframalpha.com/in...

      Neither. Its not defined.

      Now consider the equation 1/x.

      http://www.wolframalpha.com/in...

      As x approaches 0 from the left it goes to negative infinity. As x approaches 0 from the right it goes to positive infinity. This graph doesn't even suggest a value for 0/0? Is it + infinity? Or - infinity?

      I can write a function that makes 0/0 look like it should be anything I want.
      0/0 is undefined. It doesn't violate any rules of algebra. It's a rule of algebra that division by 0 is undefined.

    18. Re:Infinity by eulernet · · Score: 2

      adding a simple !=0 test is trivial and a minor part of the bigger problem.

      Wrong !
      Of course, !=0 is fine when you deal with integers.
      But when you deal with floating point values, !=0 does not work.
      This is because there are rounding errors, the zero that is displayed can be stored internally as 10^-9, and rounded to 0 because the printing function uses 8 decimals.

      You have to use:
      fabs(value) > delta
      where delta corresponds to the rounding error.
      If you work with single precision, you can probably use delta=10^-6
      For double-precision, you need to verify the accumulated rounding errors.

    19. Re:Infinity by ranton · · Score: 3

      We had five bucks, and we decided to divide it up. After we were done dividing, the money was all gone. That is dividing by zero. It was divided into zero pieces.

      Dividing something into zero pieces is not the same as dividing by zero. If you have no money left after dividing five bucks to five people, then the next attempt at dividing would be 0 / 5, not 0 / 0.

      Programmers who primarily deal with integers and money units find it natural to have anything that doesn't make sense to default to zero.

      Plenty of lazy programmers or those forced into using frameworks developed by other lazy programmers may be used to this. Perhaps even programmers forced to use primitive languages with no other options are used to it. But anyone else who knows what they are doing do not do this. This is similar to all of those developers who use NULL as if it means 0. Just because a lot of people do it doesn't make it any less idiotic.

      So in the end the answer is to use high level languages, and use money objects with sensible defaults instead of floats and ints for money values.

      Even low level languages have the capability of handling money correctly. It just requires more effort by the programmer, just like anything else done in a low level language. Considering all high level languages eventually have their code compiled down to the lowest level language understood by the CPU, low level languages are certainly capable of any calculation that a high level language is.

      --
      -- All that is necessary for the triumph of evil is that good men do nothing. -- Edmund Burke
    20. Re:Infinity by TechyImmigrant · · Score: 2

      That's why I never use floating point. It's a mess. It's impossible to achieve a uniform random distribution of floats. The space isn't uniform.
      Fixed point is nice, as long as you have an idea of how big your numbers will be.

      --
      I should use this sig to advertise my book ISBN-13 : 978-1501515132.
    21. Re:Infinity by ranton · · Score: 3, Insightful

      Let me rewrite that as:

      Rule 1: 0*X (where X = 1/0)
      Rule 2: X/X (where X = 0)

      I've had this argument often with APL fans who don't get that as obvious as 0/0 = 1 may sound, it's not mathematically sound.

      If your code ever has the expression X / X and X is capable of being 0, you have a bug in your algorithm. It really is as simple as that.

      --
      -- All that is necessary for the triumph of evil is that good men do nothing. -- Edmund Burke
    22. Re:Infinity by mysidia · · Score: 2

      We have other terms for other numbers that seem impossible. SQRT(-1)

      Sqrt(-1) is also undefined in the real numbers. It is defined only in the complex numbers.

      In the complex number system, (Sqrt(-1), 0) is just equal to (0,1)

      The complex number system is a closed field, which you won't find in a system that allows division by 0..... the complex numbers are essential fundamental to Physics and also provide the fundamental connection between Geometry and Algebra, and it's useful in particular for solving the roots of polynomials and finding coefficients, in particular the solutions of cubic equations.

      I await anxiously to see someone propose a number system where assigning a definition to X/0 makes any sense and actually has any value.

    23. Re:Infinity by HuguesT · · Score: 2

      clearly lim x->0 x^2/x = 0

    24. Re:Infinity by turbidostato · · Score: 3, Informative

      "In many situations, you can use L'Hopital's Rule to resolve 0/0.
      No, you can't."

      Yes you can.

      "At least any mathematician will look at you with disgust if you claim that"

      No mathematician will look at you with disgust by claiming that. Armchair wannabes, on the other hand...

      Because any mathematician will know this is about programing, an algorithm context and, therefore, *in many situations* 0/0 will be a context case of f(x)/g(x) as both functions' independent variable approach zero, so a limit, that is, the very scenario L'Hopital's rule applies to.

      There will be, of course, many other situations where this will not be the case, a thing both the mathematician and the parent poster are also well aware of.

    25. Re:Infinity by Jane+Q.+Public · · Score: 5, Insightful

      That is simply false. There are an infinite number of algorithms that might contain the (sub)expression X/X for which zero is a valid value of X.

      No, there aren't. There are zero algorithms were 0/0 is "valid". 0/0 is simply not a number. You don't get to make up mathematics as you go and make it a number, no matter how convenient you might find that. If your algorithm treats it as a valid number, your algorithm is wrong.

      In fact, most compilers and interpreters will barf if you try to feed them that. (Division by zero error, or "NaN", depending.) You'd have to do a bit of trickery to make it work at all.

      To assume it's a programming error is sheer unmitigated stupidity that I might expect from a mathematician that has never written a real program in his life.

      It isn't an "assumption". It *IS* a programming error. The fact that the result of division by zero is undefined is a fact of life, not just some made-up mathematical construct. You can prove that to yourself with a framing square and a couple of sticks, if you don't believe me.

      An algorithm that assumes pi is equal to 3.0 is no more stupid than assuming 0/0 is valid.

    26. Re:Infinity by serviscope_minor · · Score: 2

      If your code ever has the expression X / X and X is capable of being 0, you have a bug in your algorithm. It really is as simple as that.

      Some old code I had years and years ago needed to calculate some bits and bobs from parameters in a data file. Because reasons many parameters were often missing. So I initialised everything to 0/0, then read in what existed in the data file and did the computations.

      If for calculations where all the parameters were defines, I got out a number, otherwise, I got NaN :)

      Worked beautifully.

      If you expect 0/0 = NaN, then it's not necessarily a bug. Like a simple matrix inversion routine written in the obvious way willemit a matrix of NaNs for a singular input. That seems reasonable and bug free to me even if it can hit 0/0 eventually for many inputs.

      --
      SJW n. One who posts facts.
    27. Re:Infinity by Immerman · · Score: 3, Informative

      >Does the fact that x/0 mean that it is not solvable?

      Yes. Yes it does.

      In the most trivial simplification x/0 will be either positive or negative infinity, depending on the sign of x. If x=0 then we can't even say that much.

      It's not a matter of "we haven't figured out how to wrap it up nice and neat", it's "We've tried to wrap it up nice and neat, but determined that the behavior is *extremely* context-sensitive and provably CAN'T be wrapped up". If a function has a discontinuity in the form 0/0 then you can "creep up" on it, evaluating the function at smaller and smaller distances from the discontinuity, and depending on the *exact* details the function may approach negative infinity, positive infinity, 1, 2, -237.428, or *any* other value. Or it may not approach any value at all - some functions will have a different value depending on whether you're creeping up from the left or the right, and some will even begin oscillating wildly with a frequency approaching infinity as they approach the discontinuity, so that it's not possible to get *any* approximate answer.

      THAT is what is generally meant when a mathematician says an operation is undefined. Not that we don't understand it, but that we DO understand it, and no general answer is possible.

      It's a very different situation from Sqrt(-1), which had provably consistent behavior [ sqrt(-1)^2 = -1 ] but simply couldn't be represented on the standard number line, requiring expanding to a two-dimensional complex number system in order to represent its behavior.

      --
      --- Most topics have many sides worth arguing, allow me to take one opposite you.
    28. Re: Infinity by RavenLrD20k · · Score: 2

      Your principle isn't 0/0. It's 0/1, which is 0. You have to exist in the equation to be able to process the division, so by default there is 1 person. If there were 0 people then a Schrödinger's Cat situation emerges. Quantum supposition states that if there is no one to observe that there are 0 apples...then there are infinite apples at the same time there are none. Therefore 0/0 is undefined, and in programming should always throw an exception that can be handled gracefully (ask user to verify inputs, etc). Defaulting 0/0 to 0 in programming is a very dumb idea as it will create more problems than it solves.

    29. Re:Infinity by ceoyoyo · · Score: 2

      The IEEE did. It's called nan, and it's what most math libraries that don't die will give you back if you divide by zero. No, you can't do anything with it because it's not a number.

    30. Re:Infinity by v1 · · Score: 2

      NaN is actually pretty simple to deal with using computers. If you use 16 bits to store a signed integer, you have 65,536 units to use. One of them needs to be 0, so you have an imbalance. -32768 to +32767 is common. But you can just use -32768 to represent NaN instead, and keep things slightly more tidy when handing overflows and underflows.

      Then anytime NaN comes up at any point in the calculation or comparison, even when divided by or subtracted from itself, the result automatically equals NaN.

      Nice and simple. Now go watch Numberphile and lose your afternoon watching all his other videos.

      --
      I work for the Department of Redundancy Department.
  10. When a man is tired of checking for divide-by-zero by Anonymous Coward · · Score: 3, Insightful

    ... he is tired of life.

  11. Math doesn't approve by spiritplumber · · Score: 4, Interesting

    Division by zero if anything would be +infinity or -infinity depending on signs, not zero. A while ago I wrote an autopilot that handled division by zero by looking at the signs and setting the result to (maxpos) or (maxneg), the zero's sign being derived from the variable's last value scavenged from the PID function.

    --
    Liberty - Security - Laziness - Pick any two.
    1. Re:Math doesn't approve by spiritplumber · · Score: 2

      True, but since I knew from which direction zero was being approached, and I can't do navigation math with a NaN, I came up with that solution.

      --
      Liberty - Security - Laziness - Pick any two.
    2. Re:Math doesn't approve by spiritplumber · · Score: 4, Interesting

      Well, division by zero should never happen, but you want it to be handled gracefully in case it does. Nobody wants the autopilot in charge of a barge train to segfault. Basically, every variable in the system was stored three times, past value - current value - predicted future value. If I saw a zero, I could use the past value to get the sign of the zero, and work from there.

      --
      Liberty - Security - Laziness - Pick any two.
    3. Re:Math doesn't approve by tristes_tigres · · Score: 2

      Nope. Division by zero is NaN if and only if the numerator is zero as well.

  12. Bury Head in Sand by NickAragua · · Score: 4, Interesting

    This idea reminds me of "On Error Resume Next". The reason you don't do that is because a divide by zero indicates that you've got a logic failure somewhere else in your code. It's frequently easier to find an error when it's flashing big and red and throwing exceptions, rather than failing silently.

    1. Re:Bury Head in Sand by Anonymous Coward · · Score: 2, Funny

      He could be a mySQL programmer.

    2. Re:Bury Head in Sand by neilo_1701D · · Score: 2

      This idea reminds me of "On Error Resume Next".

      The reason you don't do that is because a divide by zero indicates that you've got a logic failure somewhere else in your code.

      Or a data input failure.

      If I'm streaming data in from a sensor, I expect there to be the odd data failure. Or lost packet. Or alpha particle hitting a memory core. Or something.

      My logic might be perfect; if the data is screwy and I pass it in to process it, well that was a silly move.

      I'd prefer 100 lines of validation code to throw out bad data before it hits the processing code than 10,000 lines of code to validate within the data processing.

      But that's just me.

  13. umm by NEDHead · · Score: 2

    no, because div by zero is not equal to zero

  14. Because 1/0 != 0? by mlts · · Score: 2

    I'd rather either have an exception thrown or a "NaN" value used than a zero returned. A divide by zero error is nasty, but just "papering over" it by returning a zero is only going to introduce more subtle bugs in the code.

  15. I'm tired, too by linuxwrangler · · Score: 5, Funny

    Hi SlashDot. I'm a programmer who is tired of sanitizing inputs and checking for exceptions. Can you suggest a way to change the world so those things don't exist?

    --

    ~~~~~~~
    "You are not remembered for doing what is expected of you." - Atul Chitnis
    1. Re:I'm tired, too by 31415926535897 · · Score: 5, Funny

      Code in PHP

    2. Re:I'm tired, too by Anonymous Coward · · Score: 4, Interesting

      Yes. I wrote a 3D modeling program a very long time ago. It involved a lot of fractions and subtracting. Lines that were perfectly horizontal or vertical would result in divide-by-zero errors, since X1-X2 in the denominator was disastrous.

      So I rotated the entire universe by an irrational number of degrees on each axis. The problem went away.

  16. Don't pretend everything's OK by Anonymous Coward · · Score: 4, Insightful

    There's a reason you're calculating a division. That number is supposed to be used for something. If your program is dividing by zero, the data it's working with is wrong. The consequences of just pretending to have a valid answer could vary from totally harmless to nuclear winter. But what's the upside?

  17. Infinity (max Float64) seems reasonable by tomxor · · Score: 3, Insightful

    Zero doesn't make a lot of sense if for instance you are dividing something by a dynamically changing denominator that hits zero at some point... the result would change from a very large number suddenly to 0.

    Divide by zero is infinity so using the largest supported number type seems reasonable for the calculation of real numbers.

  18. Re:x/0 does not equal 0. by Anonymous Coward · · Score: 3, Insightful

    No, mathematically, division by zero is undefined.

    Only engineers think it's infinity!

  19. Re:Fuck your web monkeys by Anonymous Coward · · Score: 2, Funny

    Good thing you're pushing untested code into production, Dice!

    Well, you see, they had this divide by zero error ...

  20. Maybe by Anonymous Coward · · Score: 5, Funny

    Does anyone want their div by zero errors to result in anything other than zero?

    Yes.

    No.

    Maybe.

    1. Re:Maybe by Anonymous Coward · · Score: 3, Funny

      Does anyone want their div by zero errors to result in anything other than zero?

      Yes.

      No.

      Maybe.

      Maybe not.

    2. Re:Maybe by Anonymous Coward · · Score: 5, Funny

      Does anyone want their div by zero errors to result in anything other than zero?

      Yes.

      No.

      Maybe.

      Maybe not.

      Wrong!

      Pineapple.

    3. Re:Maybe by sconeu · · Score: 2

      Black holes are where God divided by zero.

      --
      General Relativity: Space-time tells matter where to go; Matter tells space-time what shape to be.
  21. doing it wrong by FranTaylor · · Score: 2

    Would there be any serious harm in allowing a system wide setting that said div by zero simply equals zero?

    What could possibly go wrong when you assert that infinity equals zero? Well, let's see, your logic errors will go undetected, for one. If you are dividing by zero YOU ARE DOING IT WRONG. You might as well just ignore bus errors as well. And while you are at it, just ignore if the disk is full and keep writing anyway. What could go wrong?

  22. I don't think you understand the definition by Thud457 · · Score: 5, Funny
    Division by zero - how many times does zero go into a number?

    100.0 / 0 = 3
    402350.32302 / 0 = 3
    pi / 0 = infinity
    1942 / 0 = 0
    194.3 / 0 = 0
    101 / 0 = 1
    1010 / 0 = 2
    200.02 / 0 = 3
    4004004 / 0 = 4

    Somebody please submit a RFP for this to C++17 standards committee.

    --

    the preceding comment is my own and in no way reflects the opinion of the Joint Chiefs of Staff

  23. Re:Why have the post counts moved? by amicusNYCL · · Score: 2, Insightful

    Apparently so that everyone can hit some stupid Share button by mistake instead.

    --
    "Our two-party system is like a bowl of shit looking at itself in a mirror." - Lewis Black
  24. Re:x/0 does not equal 0. by Verdatum · · Score: 4, Insightful
    No, it does not equal infinity.

    The Limit as x aproaches 0+ of a/x = infinity.

    But the Limit as x approaches 0- of a/x = negative infinity.

    because this represents a jump-discontinuity, the value of a/0 is just plain undefined.

    This is like week-1 of high school precalc shit. Come on.

  25. Sighd by ledow · · Score: 5, Insightful

    You want to find out how many Euros in those Zimbabwean dollars you're keeping track of. The exchange rate fluctuates. The web-API you're using goes offline and returns zero, so you divide by zero. Whoops. How do you tell the difference between worthless numbers and just worthless currency?

    You want to draw an interlaced gif of some sort, so you do every nth line, then every n-1th line, as you get the interlaced lines and work down towards a full image with every row drawn. And then you cock up at the end, accidentally hit zero and you overwrite the first line thousands of times with garbage rather than spot the mistake.

    Zero is so completely the wrong answer, you don't even understand why. The actual real answer shouldn't even be the largest integer you can hold. And if it is, it could also be the smallest (i.e. largest negative). But actually it's none of them.

    Division by zero is NOT something that produces a number. It cannot happen. It cannot return zero (which is incredibly wrong), nor can it return any single other consistent constant. It should actually just error, which is why it does. It should produce something that's not a number (NaN). And it does exactly that.

    Divide by zero is like a null pointer. On the face of it is appears singularly useless. Why on earth would you want a pointer that you can't dereference? But it's there as an indicator. You cocked up. Majorly. If your maths is at all important at that point (a cell in a spreadsheet), then you're potentially losing billions of digits of accuracy.

    You can continue on blindly with your cockup quite easily. Any idiot can overload the divide operator to return zero when the denominator is zero. And you won't get any of those nasty errors. Errors which are indicative of an earlier error that you're just ignoring.

    There's a reason that, even back in the days of BASIC and very limited ROM space, you programmed in divide by zero as an error rather than just returning zero and documenting it. It's the same reason that you don't just "ignore" NULL pointer dereferences by saying "Oh, well, we won't call that function and just carry on from where we were then". Any idiot could make some kind of overload to allow that as well if they really wanted.

    The fact is that if you're dividing by zero you're doing something that's mathematically impossible. There is no amount of zeroes you can multiply to get anything other than zero. Not even if you multiply infinities of zeroes do you get anything other than zero. Hence division by zero of any non-zero integer is IMPOSSIBLE. It doesn't have an answer.

    And, like the square root of -1, if you just ignore it and pretend it exists you will run into all kinds of trouble. If you want to do something with it, in the same way that we use "i" to represent the square root of -1 to get lots of magical maths that actually works, use a language that recognises NaN and test against it.

    But I'll tell you now that it's quicker and easier to test if you're dividing by zero BEFORE you do the divide.

  26. Makes perfect sense by physicsphairy · · Score: 2

    2/0.1 = 20
    2/0.01 = 200
    2/0.00000001 = 200000000
    2/0.000000000000000000000000000000000000000000000001 = 0

    Exactly as you would expect!

  27. Re:The Simplest Answer... by __aaclcg7560 · · Score: 4, Insightful

    Perhaps the Big Bang was a divide by zero error? That would explain a lot.

  28. Re:Identities by Fwipp · · Score: 3, Insightful

    No, 0/0 is still undefined.

  29. Is /. getting stupider? by Kjella · · Score: 2

    Let's say I have have product sales like 4,6,0,5 and want % changes:

    6/4-1 = 0.5 = +50% ok
    0/6-1 = -1 = -100% ok
    5/0-1 = -1 = -100% epic fail

    Though I really wish you could get NULL when doing a divide by 0 in a database instead of an error.

    --
    Live today, because you never know what tomorrow brings
  30. Was slashdot hacked today? by vivaoporto · · Score: 4, Insightful
    Because it is not, and it would cause code like to fail for a = 1, b = 2 and c = 0:

    if ((a/c) == (b/c)) {
    // It is safe to assume that a == b
    }

    In a code as simple as that it is easy to spot but in more complex code this simple verification may be done in more steps or split in many different operations like:

    speed1 = distance1 / time;
    speed2 = distance2 / time;
    some_function(speed1, speed2);

    where some_function(speed1, speed2), built by other team has:

    if (speed1 == speed2) {
    // distance was the same, do something accordingly
    }

    Now, how this question was accepted as legitimate in an advanced forum like this it is amazing. Rock bottom.

  31. Eugh by Dunbal · · Score: 4, Insightful

    After 20 years of programming, I've decided I'm tired of checking for div by zero.

    I am amazed that someone can persist in a career for 20 years without a clue as to what they are doing. If you are getting divide by zero errors there is something wrong with your logic. Don't blame the computer and certainly don't try to outsmart the computer which is trying to help you by pointing this out. Div by zero errors aren't something you should gloss over, they're something that should make you sit down and come up with an algorithm that actually does what you thought it was supposed to do.

    --
    Seven puppies were harmed during the making of this post.
  32. And 2+2 = 5 by PPH · · Score: 3, Funny

    ... for extremely large values of 2.

    While you are making changes ....

    --
    Have gnu, will travel.
  33. You, Sir, are a fool by idji · · Score: 2

    You will have many horrible consequences.
    You have no idea what your code will produce.
    You will never know that your code actually works.
    As you spend a VAST amount of time debugging weird stuff, you will eventually realize it would be better if the program crashed when the error happened.

    Example from yesterday. A web-based graphing package had a field "Number of minor ticks per tick". I selected 0 and pressed ENTER. The webserver crashed with a division by zero error.
    If that software had FOOLISHLY decided to replace a division by zero with 0, then it would have gone into an infinite loop drawing the graph when it calculated the
    tickspacing to be zero...

    Example from today. I was configuring a call to a SOAP service, which was receiving an error from the Server "Division by Zero". It turned out that the error was that I had an HTTP header with no value.
    Division by Zero is an error TO BE IGNORED AT YOUR PERIL.
    Yes, both pieces of software had sloppy coding, but they both crashed, which helped me continue.

  34. Dear Slashdot, math is hard by sideslash · · Score: 3, Funny

    "Can't I just be a programmer and not understand math?"

  35. Re:x/0 does not equal 0. by RackinFrackin · · Score: 5, Insightful

    Dividing any other number than zero by zero is well defined as infinity or minus infinity.

    We need a -1 Wrong mod for just this sort of post.

  36. Re:Zero is wrong... by lenart · · Score: 2

    First issue, x/0 mathematically is infinity, not zero. Plus, you want the same exact result across all applications ever? There are certainly times where zero is appropriate, there are also many times when one would want to have some representation of infinity; yet others where this simply indicates an error of some other sort and zero is a valid result.

    Actually, mathematics does not define the result of x/0 (except in the extended complex plane or Reimann sphere, the answer there is complex infinity). I also fail to see when zero is an appropriate answer. If an application is asked to divide by zero, any subsequent result that uses the outcome of that division will not be mathematically valid. Surely one can see that the application should stop the calculation and report to the user.

  37. Re:x/0 does not equal 0. by mark-t · · Score: 3, Insightful

    For definitions of "well-defined" that selectively ignore the definitions that mathematicians use, perhaps.

  38. Re:x/0 does not equal 0. by FranTaylor · · Score: 2

    You have one apple and no people, no one gets the apple. In the real world there is no problem with this reasoning,

    In conclusion, math fails to express the natural world.

    Umm, math is not failing to express the natural world, NOT AT ALL. It is the IMPLEMENTATION of the math that fails to express. Mathematics is totally comfortable with the idea of infinity. Integer arithmetic IS NOT.

    FAIL

  39. Sounds like bugs by The+MAZZTer · · Score: 5, Funny

    caused by dividing by zero returning zero.

  40. Vague question by g01d4 · · Score: 2
    If you're programming float then what's wrong w/the IEEE standard (assuming it's supported in your implementation)? From Wikipedia

    The IEEE floating-point standard, supported by almost all modern floating-point units, specifies that every floating point arithmetic operation, including division by zero, has a well-defined result.

    Defining it to zero only makes sense where zero is also an error in the numerator, and/or zero is not a valid result in your problem domain.

  41. Special cases by phantomfive · · Score: 2

    Once a biologist, a mathematician, and a programmer were out riding in a Jeep on safari in Africa. Suddenly, there appeared, in a heard of zebras, a white zebra! This following conversation ensued:

    Biologist: "A white zebra! We discovered a new species! We'll be famous!"
    Mathematician: "Technically, we only know that it's white on one side."
    Programmer: "Oh no, a special case!"

    Programming is full of special cases. Part of being professional is learning to deal with it. There is no technology, no setting that will get rid of them for you.

    --
    "First they came for the slanderers and i said nothing."
  42. Re:x/0 does not equal 0. by Xtifr · · Score: 3, Insightful

    You only think this makes sense in the real world because you phrased the answer improperly."No one gets the apple" does not answer "how much of the apple does each person get?" The answer to "how much of the apple does each person get?"is "the question makes no sense because there are no people, so there is no 'each person'." Which is the real-world equivalent of what the mathematics says ("No answer/not-a-number").

  43. Re:Idiot by frovingslosh · · Score: 5, Interesting

    Absolute idiot. Reminds me of a time years ago when I was working at a University computer center. Despite my cultivated angry looks, a student came up to me with a printout and asked "Uh, what does this mean?" I said, "Oh, you want me to read it to you? It says: Error -divide by zero on line 50." I got a blank stare. So after a minute I further said" It means you are trying to divide by zero on line 50 of your code, which of course you can't do." That was responded to with another blank stare. So I said "look, here is line 50. See those two variables that you are multiplying together and then dividing into those other numbers? One of them must be reaching zero. Since you can't divide by zero the computer is trying to tell you that something has gone wrong. Go back, print out the variables inside the loop right before line 50 and see which one reaches zero. Then figure out why it is zero." The student said nothing and wandered away, apparently unhappy that I just didn't write the code for her.

    A few days later one of the student operators who worked for me there said to me "Remember that girl that you tried to help with the divide by zero problem? She's getting a B+ in her computer science class." Such is the state of the education system. This was a while ago, but as far as I can tell, and this post indicates, things have no gotten any better.

    No, you don't just ignore this problem and you absolutely don't put a system wide rule in effect to ignore the problem. If you get such an error it indicates a very fundamental problem wit the logic of the program. It is not trivial, and in real world situations could be deadly.

    And you don't just return the largest system number rather than zero, as some other idiots have suggested. That would be just as wrong and just as dangerous.

    And if you are really seeing this error often, I strongly suggest a change in profession to a short order chef.

    --
    I'm an American. I love this country and the freedoms that we used to have.
  44. Re:When a man is tired of checking for divide-by-z by anonymous_wombat · · Score: 2

    Or maybe after 20 years, he should stop dividing by zero, either way.

  45. Re:no by Xtifr · · Score: 2

    Honestly, I think I'd prefer having pi defined as three than have division by zero return zero. My answers will at least be in the right domain even if the value is off a bit.:)

  46. Re:x/0 does not equal 0. by Dunbal · · Score: 2

    Infinity does not exist. Real mathematicians (ie - NOT you) only speak of numbers APPROACHING infinity. So, as the divisor approaches zero, the quotient approaches infinity. You cannot have infinity as a quantity since it does not exist. Otherwise what happens when you divide infinity by zero, and is that new infinity the same as the first infinity?

    --
    Seven puppies were harmed during the making of this post.
  47. Re:The Simplest Answer... by Moof123 · · Score: 3, Insightful

    Usually it just lets the magic smoke out. A divide by zero is usually called a short circuit and makes a lot of heat for a short period of time, after that you get the smell of the magic smoke.

  48. Re:Floating point by tristes_tigres · · Score: 4, Interesting

    Oh my god, this whole discussion is so misguided it hurts my eyes to look at. Why don't you people go educate yourself about floating-point arithmetics? IEEE754 standard was designed by top-notch numerical expert and YOU IGNORE IT AT YOUR AND YOUR USERS' PERIL.

    And yeah, division of nonzero by +zero must give Inf, and there are actual useful numerical algorithms that make use of that.

  49. Re:x/0 does not equal 0. by tristes_tigres · · Score: 2

    No he isn't. He is right, too.

  50. Depends on the application I suppose. by hey! · · Score: 4, Insightful

    For certain kinds of abstract algebras division by zero is even defined, although typically as a special element like infinty, but not 0 (the additive identity element) which would lead to all kinds of peculiar situations: like 0 * 1/0 = 0, so 1/0 has to be regarded as both 1 and 0 at the same time.

    BUT if you're dealing with regular numbers or anything that obeys the axioms of an algebraic field, division by zero always represents a failure of the assumptions under which you undertake the calculation. Since it is a failure of assumptions it should always be treated as an exception to normal logic flow. If the correct -- or more accurately speaking the safest -- course of action to take is to assign a value of 0 to a calculation then of course you can do that, but that's still a case of exception handling. Building that as default behavior FORCES a certain response to an exception which of course the language designer can't possibly know is the safest response.

    In fact, even implicitly allowing division by zero in a sequence of algebraic manipulations can lead to faulty results even without actually performing the arithmetic operation in question. That's behind several algebraic "paradoxes" that have made the rounds of the Internet over the years, such as the following algebraic "proof" that "2 = 1":

    Let a = b
    [1] a^2 = a*b // multiply both sides by a
    [2] a^2 - b^2 = ab - b^2 // subtract b^2 from both sides
    [3] (a-b)*(a+b) = b * (a - b) // factor both sides
    [4] a + b = b // divide both sides by (a-b)
    [5] b + b = b // substitute b for a on the left side
    [6] 2b = b // collect terms
    [7] 2 = 1 // factor out b

    It all looks kosher, but it's not because there's a division by zero in the *algebra*. I've actually seen programs that give faulty errors because the programmer simplified expressions in ways that commit this exactly blunder. The language and compiler can't catch this because the division by zero occurred in the programmer's head.

    --
    Post may contain irony: discontinue use if experiencing mood swings, nausea or elevated blood pressure.
  51. See Goldberg's article by Hotawa+Hawk-eye · · Score: 2

    There's a classic document appropriately titled What Every Computer Scientist Should Know About Floating-Point Arithmetic. The "Special Quantities" section discusses plus and minus 0, denormal numbers, infinity, and NaN and offers some rationales for why those special values exist in IEEE floating-point arithmetic.

  52. Re:Floating point by Chris+Mattern · · Score: 2

    Well, you're fighting against the people whose opinion is, "God, I just want my program to compile and run so I can go home! Who cares if it gives stupidly incorrect answers!"

  53. Comment removed by account_deleted · · Score: 2

    Comment removed based on user account deletion

  54. While we're at it, pi by jrumney · · Score: 2

    Indeed. And my programs would run a lot quicker if pi was 4. Does anyone really want pi to be anything other than 4?