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?
Does anyone want their div by zero errors to result in anything other than zero?
Yes.
It means your code is wrong. Who knows what led up to that /0 error.
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.
Umm, wtf is this shit?
"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?
You are an idiot!!
Division by zero makes no sense, you can't tell how many times there is zero in a number. If your complex algorithm happens to divide a number by zero, it sometimes makes no sense, which you should want to avoid.
According to my electronics instructor, if we designed a circuit that divides by zero the Universe would explode.
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.
LongTail SSH Brute Force analysis tool is here!
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.
The real question is when I trigger a divide by zero, is my process in a secure state or an insecure state? If malformed input previously triggered a crash, did we just convert a denial of service attack to a full elevation of privilege attack?
...aside from the fact that it's completely wrong I can't see a problem with it.
I think infinity makes a bit more sense than zero. And max is the closest thing to infinity.
... he is tired of life.
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.
Howabout infinity?
Really?
BlameBillCosby.com
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.
I'm assuming you're talking about integers?
I've always seen IEEE 754 floats give NaN for division by zero, which is fine by me.
Division by zero with Integers (which have no representation of NaN) sounds like an exception case to me. It should definitely *NOT* be zero, if for no other reason for the fact that division by zero is undefined. If you need it to be zero in your programs, keep doing what you're doing, but in the general case, having that be the default is absurd!
no, because div by zero is not equal to zero
Divide by 0 is not 0. I would never want my results to be set to 0 for divide by 0. If anything it would need to be set to infinity, but even that will cause your data to be off.
Division by zero doesn't equal zero. It equals infinity. If anything I want to get a NULL or NaN returned. Division by zero is an exceptional case and it should be treated as such. (By throwing an exception!) Should we also make pi equal to 3 so it's easier to find the area of a circle?
Pretty sure that anything divided by zero is an uncountable infinity. You may want it to be 0, but it mathematically isn't.
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.
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
And we all know that computers are ALWAYS rational :P
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.
timeo Danaos, et dona ferentis
Please don't forget that dividing by zero is *not* always zero (or, simply, undefined) !
Anything divided by itself is one - something most everything but APL gets incorrect :-(
In answer to your last question, yes, there are lots of people who do not want divide-by-zero to be zero. Mostly because it is completely wrong and hides mistakes in what one is trying to do. A divide by zero error means there are cases that have not been considered in the design of your algorithm, equation, what-not. Masking that by silently returning not just an answer, but an answer that is completely non-contiguous with the nearby answers is a $100M-probe-crashing-into-the-surface-of-mars problem just waiting to happen.
also, lets set pi to equal 3
The reciprocal of x increases as x decreases.You want infinity, not zero, for x=0.
Il n'y a pas de Planet B.
You're asking about redefining what division means. Dividing by zero means taking the original term and putting it into ZERO groups. That is not defined. It's that simple. Now, I'm the type of person who'll discuss this, but you've not really given any reason for it to be defined as the quantity zero, so here's your chance.
Populus vult decipi, ergo decipiatur...
"Force shits upon Reason's back." - Poor Richard's Almanac
Let's go with division by zero giving an arbitrary answer, but why stick with zero? If it's floating point, it should definitely return phi. For integer types, it should return the largest legal value made up of repeating the decimal digits "8675309".
While we're at is, all boundary errors should be accepted with a simple warning of "Inconceivable!"
Oh, and we need seven red lines, all of them strictly perpendicular, some with green ink and some transparent. Oh, and one in the form of a kitten.
"Does anyone want their div by zero errors to result in anything other than zero?". I think the answer is yes, a divide by zero is NOT zero, it is an error. I would like my divide by zero to generate an error.
I can see that only if you try 0/0... the fact that you're trying to divide should have precedence over the fact that you're trying to divide it. Otherwise, if my application is trying to divide a number by, well... nothing, I'd like to have an exception please. (basically it's like saying "could you please do a divide operation to not divide my value please)
Yes, I want it to result in NaN.
Wouldn't it be 1?
For all n, wouldn't n/n=1 ?
When I get a divide by zero error, sometimes it is because I made some other error such as mis-spelling a variable name or maybe my database connection is broke. Less of an issue with TDD or BDD, but it makes me go back and evaluate if I really expect zero to be a valid value.
(score : -Nan), flambe'
It seems like catching SIGFPE and handling the floating-point/int div-by-zero cases specifically could help you work around this.
The problem is that it is actually an unknown value.
Infinity is closer to the math answrer, but that takes too many bits to encode.
Dividing by zero is, by definition, undefined, why would you want divide by zero to be equal to zero? If you don't trap it and handle it appropriately, you'll be generating undefined results.
What is the use case for having divide by zero equal to zero? (except, perhaps for 0 / 0 where you really want it to be zero, but I can't think of any other case where having any number divided by zero equal to zero would give correct behavior).
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?
Wow comments actually work again. Good thing you're pushing untested code into production, Dice!
Great idea !
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.
Dividing by zero *should* crash your program.
What if you were depending on the result of that division to determine which function to call.
if(x == 0) doThis();
else doThat();
An incorrect result of 0 could lead to unpredictable results, which is bad for a program. It's better to make sure your input is clean so it doesn't come up in the first place.
>>Does anyone want their div by zero errors to result in anything other than zero?
Yes. Almost everyone.
I've often used "1" as a drop in when dividing by zero. also the logarithm of zero, i usually am working with information units, so it's plnp, and if p = 0, i just say that plnp = 0, and that's kind of like saying ln0 = 1.
i think mathematically infinity or negative infinity would make the most sense, unless its 0/0, in which case you'd apply l'hopital's rule. but i don't think the computers going to do that. another way is you could create another number system, that would run a tally of divides by zeros or multiplies by infinities, minus multiplies by zeros or divides by infinity. (and flipping the sign on negative infinity.)
It is bad because given some function f(k) = 1/k the last thing you want to do is to have S(x) = f(x-5) + 3 return 3 when x = 5 instead of a BIG FAT ERROR.
The same reason you can't divide by zero in mathematics is the reason you cannot reassign divide by zero in computing. It's a logical impossibility. Making it possible (for example, in the famous "proof that 1 = 2") turns whatever logic you are using the result of a division by zero into a train wreck of causality.
Unfortunately, no, you can't just say screw it, from now on x/0 = 0. If the divisor, for example is an hourly rate and you're trying to calculate hours worked from total pay, the fact that one record contains a zero may mean deeper problems exist that deserve to be flagged.
If you haven't learned the general principle of checking shit after 20 years...
Yes, what could possibly go wrong from no handling a dive by zero. https://en.m.wikipedia.org/wiki/USS_Yorktown_(CG-48)
The harm is that it's not mathematically correct, and it's never a good thing to hobble the correctness of a program just because the coder's too damned lazy to validate his data.
Does anyone want their div by zero errors to result in anything other than zero?
<audio voice="Samuel L. Jackson">Hell yes.</audio>
What do you mean by equal to zero? there are well defined values for division by zero: Inf and -Inf for nonzero/zero and NaN for zero/zero. Having x/0 = 0 is worse than useless, it's mathematically wrong.
I'd like it to return an error, because it does not equal zero. It is undefined.
I know that in a business setting, making x/0 = 0 would be okay. At least it has always been okay in my 30+ years of experience. But I think the problem lies at a very low level, that is, the CPU cannot divide something by zero. I am pretty sure this is why it is, universally, an error.
Proverbs 21:19
The only problem I see is that Zero (0) is something. It's possible you could get the community to agree on a specific failure value (-492687 as an example), but then you still have the issue of what defines a return for a div-by-zero attempt. So yes, divide-by-zero returns could be tested for and defined in some other manner, but the problem is what happens when existing code actually relies on the return value you've decided upon?
There is no problem with having a default, as long as it corresponds to raising an exception.
The right decision when encountering a division by zero depends on the numerator and the meaning of the division, i.e., whether it can be seen as a limit or not.
> Does anyone want their div by zero errors to result in anything other than zero?
Yes. Your proposal is actually one of the worst things you can do in general: only when the division by zero can be seen as a limit *and* the numerator goes to zero faster is this even to be contemplated. Even then... signed zeros.
(All of this is well-known of course.)
Resume Next
What could possibly go wrong?
This sig left unintentionally blank.
No, mathematically, division by zero is undefined.
Only engineers think it's infinity!
Does anyone want their div by zero errors to result in anything other than zero?
Yes.
No.
Zero is kind of the opposite of the actual correct value, which is infinity.
Having a default is fine, *if* you can change the setting. In ARM processors, you have just that; you can set a flag on the processor telling it to raise/not raise a DbZ exception.
Does anyone want their div by zero errors to result in anything other than zero?
Yes.
No.
Maybe.
Why not change ++ to result in incrementing by 100 instead of 1? What's the harm with that?
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?
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
So then you would have to add to every instance of a potential divide-by-zero a check for zero result. And worse still you would have to try and differentiate that zero from other zeros. In any case a divide-by-zero produces infinity, and infinity is certainly not quite the same as zero. In short, this is an idiotic proposal.
as most people have said, the "correct" answer is almost always +/- infinity. However, the Limit as x goes to 0 of x/x is 1!
But x/0 does not equal zero. It is undefined and assuming it is always zero is actually wrong.
I don't think you can stop it for the whole program, as the error might be thrown by the CPU itself.
Instead of checking for division by zero, you need to figure out and stop how a zero is getting there in the first place. You have a bug somewhere else in your program. Find it.
Aside from all the other issues that have already been posted, another problem is that different systems will have different defaults . Makes stuff just that much less portable.
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.
Those of us who wrote for PowerPC may recall the architecture returned 0 for integer division by 0. It's been done before and, in my opinion, was a good trade off between mathematical purity and pragmatism. The vast majority of the code I write follows the pattern result = (denominator != 0) ? (numerator / denominator) : 0.
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.
If the worst that can happen is a wrong pixel in a computer game, then that's fine. But if I'm analysing data to be published in a scientific paper, dividing by zero means an error in my program, and I want to know about it and fix it. It doesn't really matter whether it gives a nice error message or a core dump, but it must be noticed.
2/0.1 = 20
2/0.01 = 200
2/0.00000001 = 200000000
2/0.000000000000000000000000000000000000000000000001 = 0
Exactly as you would expect!
When things get complex, multiply by the complex conjugate.
Exactly, and if it was not an error, I can see 3/0 = inifinity, or very worst case 3/0 = 3 (you're not dividing after all) but never 0
Not only is CodeInspired a complete moron for asking such a stupid question, but Timothy is also completely stupid for posting it. Something this idiotic does not deserve to be posted. It's not a good idea. It's not even a sorta, kinda, maybe a little bit okay idea. It is an absolutely, completely, 100% moronic idea. You should both be ashamed of yourselves.
Let me guess. You secure credit card data with your programming.
First, division by zero is undefined in mathematics.
You MUST throw an exception, and handle it appropriately, or you are headed for bug hell.... google the plight of the USS Yorktown and a zero-divide unhandled exception if you need a real world lesson.
Second, IF you were to entertain the thought of actually returning a value, zero is the wrong value. (set mode=mathematician)
The limit of 1/x as x -> 0 is infinity if I remember correctly..... It has been 35 years since that particular class.....
In measure theory, a positive number divided by zero is defined to be infinity, and there's likewise a negative infinity. OTOH, in complex analysis there's a single point at infinity. I'm sure there are other well-defined notions of infinity, and you can dig deeper into things like compactification. However, none of the definitions of infinity is equal to zero, for the obvious reason that 0 times 0 is still 0. Also, you need rules such as infinity times zero being undefined, so by having a numerical value for infinity (like NaN) would just push the problem further. The unfortunate fact is that the set of real numbers is not closed with respect to division, and you have to deal with it one way or another, rather than hiding the problem.
Escher was the first MC and Giger invented the HR department.
In my world, x/0 is usually infinity. This almost always the case in Calculus. An exception being l'hopital's rule where it can be a number.
Normally, something is wrong either in code or with my data if I encounter an unexpected division by 0. I would rather catch it and log an error than continue my computations with an incorrect 0 value.
Even in basic algebra, it isn't computed to 0. Graph out y = 1/x. At x = 0 it if both negative and positive infinity.
I don't want the default to be that, but if you write a function that way it better be clearly documented and adhere to the following statement.
f is the function containing /0 returns 0 iff f(x) does not contain 0.
This must also be communicated clearly and concisely to anyone using the function.
How many of those years were in elementary school?
Do you have any background whatsoever in CS or Mathematics?
When I see a divide by zero, it's a damn exception; alternatively it's NaN.
Just off hand I can't fathom why you would want the answer to be Zero.
Legacy code for a lot of programs will cause problems.
Honestly, I would create a new symbol that would count as a number, just as "i" is a number - the Square root of -1.
Call it NEL. Divide anything by 0 and you get NEL. The use of any and all other math operations on NEL give you NEL (NEL+1=NEL, NEL/NEL = NEL, etc. etc. etc. )
Now you have a mathematical symbol for - shall we call it 'bad math' that does not result in an error. Probably useful in a lot of other cases as well - just as "0" itself was a useful mathematical concept.
Maybe we could expropriate a 0 inside another 0 for the symbol of NEL.
Any time there's an error, just skip it and go to the next instruction.
Bam. No more errors.
Is this a real question or are they just screwing with us?!
Most linux users don't know this, but the man pages were named after Chuck Norris. Chuck Norris fsck'ing hates noobs!
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
With Java, your program will fault when encountering division by zero. Even with C++ it should be possible to trap this exception.
If it happens, _you_ the programmer fucked up the logic of your program. However, if you're trying to prevent / discover this in every single division throughout your program, you're doing something wrong.
Think of your error handling code as risk as well as any other code. Does it make sense to make code for everything that might happen, or does it make sense to just give up on some level and move on?
After 20 years, you're experiencing fatigue. If you haven't realized your code will never be perfect, and it will be replaced as soon as you're gone (hopefully), then maybe it's time to realize this and simplify your life, and code.
That comment made me laugh so much! "I do not like the result of a division by zero! Let's change maths!"
Awesome!
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:
where some_function(speed1, speed2), built by other team has:
Now, how this question was accepted as legitimate in an advanced forum like this it is amazing. Rock bottom.
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.
No.
lim 1 / x =
x 0
Dividing by zero means your dividing by nothing, which is a logic error. It doesn't cause the thing your not dividing to become nothing.
... for extremely large values of 2.
While you are making changes ....
Have gnu, will travel.
A number of languages have some sort of "if A is null use B, else use A". For example in C# you can do "myVar = subject ?? defaultValue". Perhaps extending that syntax to include divide by zero? so, "myVar == a/b ?? 0". Or, for a more explicit exception handling syntax, something like myVar == a/b ?? DivideByZeroException 0"
Then at the OS and code execution level, the divide by zero still throws an exception, but at the code level the exception is handled in a compact manner.
Of note, C# 6.0 has a number of language extensions for handling null reference, such as "myVar = value?.Substring(0, Math.Min(value.Length, length));" so adding another one for DivideByZero isn't so shocking.
I implemented a floating-point package years ago on a system whose integer CPU did not support floating point. I returned as close to infinity as I could--the largest floating-point number. Mathematically incorrect, but for its purpose, this worked just fine.
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.
"Can't I just be a programmer and not understand math?"
after 20 years of programming you should also be tired of checking for SQL injects, or out-of-range errors, but you had better not stop checking!
"My code is shit, I keep getting div/0 errors. What kind of hack can I put in place so that I can continue to produce shit code without getting these errors?"
Division by zero isn't equal to zero. It isn't equal to positive infinity. It isn't equal to negative infinity. the value of any number divided by zero (including 0) is that it does not exist. After all, doesn't any number divided by itself equal to one? So shouldn't 0/0 = 1? No, because you can't divide by zero. The proper way for a computer to respond to an attempt to divide by zero is, "I have absolutely no idea what's going on here. I speak math, and you just asked me to do something that is outside of the language of math. I am going to either crash so I don't do anything stupid, return a reserved value that explicitly indicates that the answer does not exist, or jump out a level, throwing a runtime exception (as appropriate for the given language), and let YOU tell me what to do now. It has to be this way because there is never a single answer that always holds true about what a computer should do when encountering this.
This should be hammered into you first in precalc, and again in any first-semester intro to computer science course, and again in discrete structures, and again in a computer hardware course. This is the reason for a lot of the hostility for asking this question.
Why not treat null numbers as 0? Or "" as a null string or vice versa? Or do 20 place decimal calculations without considering the concepts of accuracy and arbitrary precision?
A div by 0 is a fuckup. Unless you considered its effects in a specific context and deemed it to be OK, in which case you already wrote the code to handle it.
I actually want to know when there is a pathological / exceptional condition.
As it happens, I run into this problem very seldom, I am not troubled to check for it, and I handle the situation as needed.
Also a system-wide setting just seems like a bad idea. Use a per-process or per-thread setting if you must, if what you're looking for is even possible.
Anything divided by zero is not a number.
If you end up with a div zero, you should have handled the case in a special way.
In some cases it can be correct to treat the result as zero, in other cases the result should be infinite. Sometimes it should be 1.
I've been shopping at the supermarket for 20 years, and sometimes they don't have what I want, and I have to do something else. I tried to buy bread the other day, and the clerk told me they were out. Whenever they're out of bread, I substitute potatoes. Why can't the clerk just silently give everyone in the world potatoes instead of telling people they're out? I'm really tired of having to handle this special case of being out of bread and then get potatoes. Does anyone else in the world want to be told they're out of bread when a store is out of bread? Doesn't everyone just want to get potatoes instead?
Is Dice trying to get the answers to tech interview questions now? If you really want to silently ignore all errors, no matter how badly your application's logic has gone off the rails and no matter how crazy your application might act due to not knowing what the hell is going on, you can code in VB and add "ON ERROR RESUME NEXT" at the top.
Suffice it to say, it's generally a bad idea to have the program continue on even when it should know that it no longer knows what it's doing. But hey, as long as it only erases your bank account or whatever, you can code any way you want.
As they say, garbage in, garbage out. If you silently ignore garbage coming in, guess what you get out of the program?
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.
Math is not expressive enough to handle the real world, since division by zero can occur without causing a problem. Example: you want to divide apples among people. You have one apple and two people, each person gets half an apple. You have one apple and no people, no one gets the apple. In the real world there is no problem with this reasoning, it's only that math fails to handle it so you have to include extra code to make it come out. In a real life situation, you need no extra error-handling because there is no error. In conclusion, math fails to express the natural world.
What you're asking for is equivalent to the "on error resume next" feature of Visual Basic.
If you just barely know how to operate a fork-lift, you will not get a job operating a fork-lift.
... but if you just barely know how to program computers, you'll get a job programming computers just fine because the management can't tell the difference between a true programmer and a coder who just hits keys on the keyboard until something looks like it does what it's supposed to do.
If you just barely know how to fly an airplane, you will not get a job flying an airplane.
If you get a divide-by-zero error, it's not because the computer made a mistake, it's because you made a mistake.
For definitions of "well-defined" that selectively ignore the definitions that mathematicians use, perhaps.
File under 'M' for 'Manic ranting'
divides by zero the numerator no longer ever existed.
How the hell does that make the Slashdot frontpage ?
This is one of the most stupid questions I heard in my entire life.
You, sir, are an idiot.
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
Actually scientist think it infinity.....engineers will do if{} else {} to meet the specification....coders just catch the exceptions and return "unable to process".
caused by dividing by zero returning zero.
In a business setting, x/0 does not always equal zero.
Sure, there are cases where it does, there are many cases where it does not.
I'd much rather the system throw an exception so I can handle it as needed for my specific task.
Now, what I would like, and what some environments provide, is a way for me to trap an exception and handle it myself. I've never had to trap "/0" but I assume it could be done if my program was suitably privileged.
Knowledge is how to play a game, intelligence is how to win, wisdom is knowing what game to play.
This might make more sense if you're using floating-point, where zero might represent the range -epsilon/2 to epsilon/2. In this case it might make sense to return a value on the assumption that a zero value isn't possible, and any value would be correct, although wildly imprecise.
Who ordered that?
and typing of variables then?
I mean I quite like them in their place, like commenting and indenting - they seem nice to have and something you *should* do.
But... well we seem to have taken it a bit far. We let compiler/OS handle so much for us and yet we seem hell-bent on preserving this 'nickety' little annoyances.
Sorry no. The error is in your answer.
Dividing any other number than zero by zero is well defined as infinity or minus infinity.
See. It can't be defined as one of two different things, especially since neither of those things are a number. Except that you're probably joking, right?
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.
3/0 = infinity *could* be true in certain circumstances (math involving infinity is wonky, though).
3/0 = 3 can't be true in *any* circumstance, because that would also mean that 0=1.
Does anyone want their div by zero errors to result in anything other than zero?
Yes.
No.
Maybe.
Can you repeat the question?
There's a reason the IEEE floating-point spec defines non-zero/0 to be infinity and 0/0 to be NaN.
For non-zero/0, infinity is the "correct" answer and anything else will give strange results.
For 0/0, the "undefined" case, arguments can be made for any value depending on the situation. Often, there's a value that makes the result of a large computation continuous. When computing the sinc(x) = sin(x)/x function popular in signal processing, sinc(0) = 1 is correct.
But the ALU computing 0/0 doesn't know what the right value is.
If you are dividing by zero in the first place you are doing it wrong. You should never be throwing divide by zero errors; because doing so means you've already failed.
You should know you have a valid denominator before you attempt the division.
In other words, ensure your denominator is non-zero before you divide rather than trapping divide by zero errors, because if your code is asking a computer to divide by zero you've already fucked up somewhere else.
IIRC we use a Texas Instruments DSP in some of our products that returns zero on divide by zero.
Seems to work fine, except that it trips you up when porting from the DSP platform to e.g. a PC platform where the divide-by-zero behavior is different..
I work in performance management and often we do a successes/opportunities calculation. Often when there are zero opportunities, that is a good thing ("Number of server crashes resolved without user impact"). We do not want 0/0 to evaluate to a 0% success rate, that should default to a 100% success rate because there were no failures to unsuccessfully respond to.
because apparently people who have been programmers for 20 years don't know why a number divided by 0 isn't 0
To get this functionality all you have to do is switch to using old school Visual Basic (not VB.Net) and include:
ON ERROR RESUME NEXT
In all your files. You will never be told when you have a problem ever again. Even better this applies to more then just divide by zero, it work for null pointer exception, integer overflow, ignore all the errors!
multiplication is a more complex addition...division, i'm told by the internet, is a more complex form of subtraction. we subtract the divisor from the dividend and continue until we reach a point that no whole divisors appear, and that is our remainder. personally, I kinda find this moronic. at divide by 0, you subtract zero from the dividend, and get an answer...a unity...the same number split into 0 pieces. The undefined in the computer (so says teh intertubes) is that this complicated subtraction is continued ad infinitum until exception and halting...for undefined. i also believe that the type of zero you are talking about is VERY important, as like infinity, zero is not a number but a concept...and given humanity's provincial "never being wrong" attitude...i ask this...could there be more than one type of zero? In Newtonian gravity, divide by zero when the distance between two objects becomes zero results in "undefined". Personally, i look at this event in my head and realize that if the two objects are 0 distance apart, you could easily (depending on composition and actual mass) you would no longer have two objects...no distance between centers of mass, since you only now have one mass. This zero specifically refers to the distance between two bodies of mass moving towards each other...wouldn't the equation change once there is only one body, no distance to travel...just a unified single object possibly in motion? so this is going to get a little into sort, quicksort, and heapsort arguement. what kind of divisions would result in actual numbers, should we simply change how we divide? how about removing single units into a number of piles equal to the divisor and the remainder is still the same? In this scenario though, it would seem to give a real answer though, instead of getting stuck in a loop because we programmed everything to 'kernel panic' and can't decide when to stop subtracting nothing...dividing into no piles...no division when 0 in the denominator. So if it's a 0 of a distance, would indicate no distance...if it's a zero of a charge, would indicate no charge...if it's a zero of mass, it would indicate no mass... *shrugs*
There are three kinds of people in the world. Those that can count, and those that can't.
20 years of programming, and you can't see the harm in this? I suspect that 20 years of programming is actually 1 year of programming, 20 times.
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."
0/0 is when God is telling me my project will not succeed. Don't cut her out of the conversation!
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").
42
Or maybe after 20 years, he should stop dividing by zero, either way.
Which means no division takes place. You are not dividing by zero, you are avoiding the division entirely, since the denominator is zero.
Which is exactly how "the math" would handle it.
"Mind, as manifested by the capacity to make choices, is to some extent present in every electron." -Freeman Dyson
No you fucking hipster idiot. If you're really coding for 20 years, this can only mean this is some shitty attempt to get coverage for your pathetic existence.
You can't possibly be so stupid to ask this question after 20 years of coding.
Fuck you.
Easiest way to see this is by graphing 1/x
https://en.m.wikipedia.org/wik...
Notice from the negative side y is approaching - infinity as x nears 0, but from the positive side, when x approaches 0 y is becoming + infinity.
So it's not the same as multiplying by 0 where everything results in 0. It's really and truly undefined. You can't average +/- infinity and get 0, it's the gap between them. It doesn't exist.
If you ignore a divide by zero, your results will be unpredictable and often nonsensical. For example:
The classic algebra trick to "prove" 1 = 2
Cwm, fjord-bank glyphs vext quiz
Add a special operator that implies division by zero is zero. I propose /.
Division by zero creates an answer that is beyond the range of whatever finite field number set you are using. It must generate an exception as it cannot be solved with the range of numbers that the machine is using.
Always remember that all math you do within a software program has to play nicely within the defined boarders of the number sets used by the compiler. The program fails if it traverses outside of this boundary.
The resulting NaN and exception (eg. fault signal) is correct and should not be changed.
(Note: I am not including mathematical modelling languages which may have some concept of a non-finite number field.. not aware of any existing anyways...)
- I stole your sig.
Any default value assigned is not logical nor correct. Sure you might understand the hack but what about the next developer? Best to determine and fix what happened beforehand, what caused the /0 situation to exist in first place.
Anything less is simply a hack.
Congratulations, moderators.
Slashdot has officially jumped my shark.
This was such pure drivel I can no longer even read you in private, the embarrassment is so great.
Goodbye.
On some CPUs divide by 0 results in 0, as there is no remainder operation you compute it by multiplication and subtract. ie.
x % y = x - ((x / y) * y)
Imagine a hashtable like operation:
buckets[key.hashCode() % hashtable.length]
If the table is empty then length may be 0. As divide by 0 is 0 then:
x % 0 = x - ((x / 0) * 0)
= x
This results in memory accesses corresponding to the key's hashcode. The behavior was undefined but rather than accessing the 0th element, as it would say on x86, it can result in crashes...
There is just such a switch. It has [0/1] printed on it, and is often quite large. If you want 0/0 to be zero, set this switch to the 0 position. If it's a push button, you may have to push and hold it for ~6 seconds.
A few years back I made a pretty important report that listed percentages. At the time it didn't seem to matter what happened when data was missing, so I created a function that would take a numerator and denominator and spit out 0 if the denominator was 0. (This was in SSRS, so I couldn't use IF since it processes every part of the function regardless of the boolean outcome.) Looking back, while this hasn't caused any problems that I'm aware of, I regret the decision. Displaying -- is actually more informative than 0%, because it tells the user that the data is not available, not that it's 0%, which can be misleading.
Some day I'll fix it when I have time (and am not browsing Slashdot), but my word of warning to you is: don't. /0 is a special case, and should be treated specially. Don't care about the output? Check for a 0 denominator and just return 0 immediately. But don't try to do this globally, because one day you will need to handle /0 specially, forget to, and that kind of setup will bite you in the ass.
That way we can check for errors just like with any system call or C function that can have 0 as valid return value.
watching all these nerds freak out over nothing is hilarious. You'll probably be fine.
I take that the OP is neither a mathematician nor a physicist (as i am). NaN is a reasonable "Default" value for 1/0, and has the advantage that it propagates without you checking for it.
A physical or engineering simulation which divides by 0 should return NaN or terminate.
And yes, the serious reason would be that if an engineer uses ANSYS to validate if the bridge is structurally stable, i donâ(TM)t want that some asshat intentionally accepts bad meshes (i.e. meshes with "empty/zero sized cells" without errors.)
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.
Whenever you divide by zero, the problem ISN'T the division - it's the previous code that either assumes that dividing by this number will produce a valid result, or is doing something wrong in turn.
Checking - and somehow kludging - a divide by zero does nobody any good. You have to ask WHY you're dividing by zero and what it should mean.
I *want* divide by zero errors because they inform me that I'm doing something wrong elsewhere.
(And even if you wanted to kludge it - returning a very large number would be a better choice than zero...but don't do that).
Bottom line - if you're doing lots of div0 tests then you're doing something wrong in many other places!
-- Steve
www.sjbaker.org
The Limit as x aproaches 0+ of a/x = infinity. But the Limit as x approaches 0- of a/x = negative infinity.
Incorrect.
The Limit as x aproaches 0+ of a/x = approaches infinity. But the Limit as x approaches 0- of a/x = negative infinity.
Seven puppies were harmed during the making of this post.
You have one apple and no people, no one gets the apple.
Uh, no, you get to keep the apple. It doesn't magically disappear. If there's no people, then there's no apple, because you don't exist either.
There has been a lot of talk about how division by zero should be interpreted in mathematics, with real numbers; the concept of limit has been touched.
What I'd like to hear would be some proper math guy's interpretation of this issue, how pure integer maths (discrete math?) treats this? All I personally can think of would be the a = divider × quotient + remainder thing. We know that anything times zero is zero, which leaves a = remainder; quitient may be any value, so strictly zero is not incorrect in this regard.
If the Original Submitter can't even *imagine* when x/0 shouldn't return 0, then the Submitter's error handling must necessarily ALWAYS return 0. Ironically, this means that his/her code wouldn't suffer one bit and might actually improve by some benchmarks (it never handled x/0 properly, so it'd at least reach its incorrect result slightly faster)
"0" is typically as far as possible from the two possible vaguely sensible numeric results (MAXFLOAT and NEGMAXFLOAT) unless the Submitter SO consistently fails to handle indices (in loops, etc.) correctly that a zero index is overwhelmingly the cause of their DIV BY ZERO.
Keep fighting the good fight. We can all benefit from alternate views on the basic math -- but this submitter's problem is a terrible coding style
Well, in the real world you also can't give two apples to half a person, so this whole analogy is pretty off.
The Quirkz Handbook of Self-Improvement for People Who Are Already Pretty Okay
Except, if there is no one there to divide the apple by, then there is no division.
Real world says if there is no-one to get the apples, then no division needs to be done. Not just go ahead and defy logic.
Yep. Capture the zero, and with some proper insight you set it to some appropriate non-zero approximation of zero like 1e-6 or 1e-15. The choice usually reflects knowledge of the situation at hand. But often I'd rather a program stop and tell me something bad has happened rather than just patching around it and carrying on.
After 20 years of programming, I'm tired of checking all the return values of all the functions I call. Is there a way we can agree that functions should never return an error? Is there ever a case where you want a function to return an error?
Or a +1 Dope Slap button.
"I'm a lazy bastard. Can anyone make my job so easy that I can just sleep at my desk for eight hours instead of working? I don't actually care about the quality or correctness of my work, I'm just tired of having to actually work for a living."
I do not fail; I succeed at finding out what does not work.
And you are still allowing laziness to overshadow reason? The idea you have 20 years programming experience is seriously suspect if you think of adding a "system wide" default for divide-by-zero AND think it should be adjustable. It's so absurd you may have stuck my eye wide open in an expression of shock.
We need a special big stick to slap morons like RackinFrackin for ignorant comments like the one above . What's worse, he is "correcting" someone who knows better than him.
You end up in undesirable situations like having a share button on slashdot after each story.
No he isn't. He is right, too.
The obvious answer is that returning 0 for 0/0 would be a lie.
while(1) attack(People.Sandy);
At the risk of incurring the wrath of "the old ones" of programming, why on earth not? Multiplying by 0 results in 0, so dividing by 0 could equal 0 too. Better still, if you're dividing it by 0, then you're not even dividing it at all, so perhaps the result should be the number other than 0? And if you're dividing 0 by 0 then the answer should also be 0.
"Well defined" is poorly defined here.
System-wide default error handling would actually be useful. It is completely up to the programmer to make sure nothing unexpected happens, but that is true even without the feature. And it isn't as if there is no default already... it just isn't customizable on a system-wide or better yet, scope basis (in most languages).
This isn't about invalidating any logical tenants. It is still up to the code to know how to handle errors. For there to be easier methods of instructing default behavior cannot be a bad thing.
You do not really understand your real world example. You are switching reasoning, which is exactly what the software is doing:
4 apples for 4 people -> each person gets 1 apple
4 apples for 2 people -> each person gest 2 apples
4 apples for 1 people -> each person gets 2 apples
4 apples for 0 people -> each person gets ???????
Because the formulation you did use does not work in this case you switched to:
4 apples for 0 people -> no one gets an apple
You use an exeptional form of answer in this case in natural language.
Software does the same, it reacts in an exeptional way.
Division by zero has no meaning as a direct computation and will most of the time cause an exception.
Whatever factor is being divided, it must have a special case when the divisor equals zero.
Like for example:
X / (Y == 0.0f ? 1.0f : Y)
X / (Y == 0.0f ? X : Y)
It will always depend on the factors being computed, their meaning, and the context in which they are being computed.
A system wide default value would remove that nice exception and then you will have to check by hand every division looking for some 'unknown bug'.
In any case, you DO have (at least in windows) a way of setting your own exception handlers and just do nothing when the exception is raised, although you lose your current execution context, but hey, if you have to ask...
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 // multiply both sides by a // subtract b^2 from both sides // factor both sides // divide both sides by (a-b) // substitute b for a on the left side // collect terms // factor out b
[1] a^2 = a*b
[2] a^2 - b^2 = ab - b^2
[3] (a-b)*(a+b) = b * (a - b)
[4] a + b = b
[5] b + b = b
[6] 2b = b
[7] 2 = 1
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.
I can think of at least one scenario where it makes sense. Say you're building the next Curiosity, you've done all the right things, dealt with exceptions, quality assurance, code reviews etc.. Wouldn't it be better if an exceptional divided by zero exception wouldn't brick your rover by default? All the bashing, I think it comes down to priority.
dividend = 0
divisor = 0
if (divisor == 0) { alert('cant do that!') } else { // go on }
log a warning? error?
trace the data back when it happens and find out wtf wtf means?
In C and C++ it's not defined to throw an error. It's undefined behaviour and the compiler is free to do whatever it wants.
Typically that means doing nothing special, and on x86, the instruction itself traps when zero is the denominator. On powerpc, there's no trap and you get zero. Each processor has a different, defined behaviour.
However, if the compiler can prove that, along any particular path, the denominator is guaranteed to be zero, it's allowed to delete that entire path, as the program is undefined if that path is followed, so it can assume it isn't followed. It's not guaranteed that your program will execute normally up to the divide by zero. A soon as the divide by zero becomes inevitable, the program is undefined and the compiler is free to do absolutely anything.
If any of the above scares you, C and C++ aren't the languages for you. It always amazes me how many people write non performance critical code in C. But when you need speed/efficiency, there's no replacement for C or C++ and a good optimising compiler.
Also, to the original poster, no, defining it to be zero doesn't make sense. PowerPC did indeed do that. But the number desired isn't always zero. It's undefined in mathematics for a reason: in different situations, it logically should be a different value, and there's no way to resolve the contradiction. Hence if you do divide by zero, your program is seriously flawed.
Here is a code snippet which, when translated from this sudo-code into a real language, will always return 0 instead of div/0 errors!
try{
foo = bar / baz
}
catch{
foo = 0
}
...Had this been an actual emergency, we would have fled in terror, and you would not have been informed.
Stop using raw data types?
Rather than putting 'magic' or just wrong values in the result, values should have quality flags associated with them, such as
uninitialized
overrange
underrange
infinity (+ and or -)
undefined
propagated bad quality from previous operations with other (bad) values
-others
If a quality flag is set, something is wrong.
CODE COWBOY!
Yeeeeeeeha!
Code Cowboy thinks to himself "I could either get the shit out of my code so it's works right or I could just wrap the code in tinfoil, spray on some gold color, put some air freshener on to cover the stink and call it a gold brick instead of a shit brick!"
That's the way you do it, money for shit, get your cocaine for free! I want my, I want my, I want my code cowboy attitude!
Ever heard of functions? In _your code_ if you need a certain behaviour to repeat over and over, ie. because you need a certain number to become 0 when not distributing something out to anyone, you make a function for it. Your function, your rules.
Math is just a tool. In the right hands it can do wonders. In the wrong, you can prove anything by misuse, confusion and diversion.
Anything divided by zero is by definition infinity. Not zero. I definitely do NOT want your default anywhere near me. If you can't represent the division by zero as infinity or handle otherwise as a special case that does NOT result in any numeric value the program should CRASH or THROW AN EXCEPTION. Period.
leather-dog muksihs
Blog: @muksihs
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.
One of my math professors worked for some kind of engineering firm in his earlier days. This was probably back in the 70s or so.
They were creating some kind of device and it was based on a math theorem of some kind--the usual thing where there are hypotheses A, B, C and **if those are exactly fulfilled** then there is a little algorithm you can use to give result X, Y, Z.
So his fellow engineers used this theorem, using the algorithm and result X, Y, Z but blithely ignoring the need to check that hypotheses A, B, C were fulfilled.
Prof warns fellow workers that this isn't going to work and is a recipe for disaster.
Fellow engineer-workers can't understand what the problem could possibly be, so proceed to manufacture the device as-is. It is some kind of hard-wired measuring tool or such, with custom manufactured circuit boards that bake in the programming logic etc etc etc.
Result: Device worked perfectly most of the time but occasionally, randomly, mysteriously completely malfunctioned. Of course--it worked perfectly whenever the hypotheses were fulfilled and complete malfunctioned otherwise.
Other result: Firing of numerous people on engineering team and complete re-design of the device from the ground up.
To answer your question: The reason not to follow your plan is that ALL of your programs are going to behave like this device. They will work fine most of the time (if you are lucky) but then there will be random and very-difficult-to-detect bugs that appear only during certain relatively rare and difficult-to-duplicate circumstances.
In short--nightmare material.
Why stop there? If I get a file exception it should just write to syslog by default! If I have a null pointer it should just write to the last array I referenced! Array out of bounds exceptions should cycle back around to the start of the array so I never see that error either! I'm sure nothing bad would ever happen ever from implementing all of these!
Seriously son, it's called an error for a reason. Correct your invariants so it can't happen or monitor for the exceptions and handle them gracefully. It's bad enough that incrementing an integer past its max wraps it back around to its min. Let's not make coding even more treacherous, m'kay?
Division doesn't really exist in the sense of a mathematical operatoin. Division is best thought of as a convenient shorthand for multiplication by the multiplicative inverse of a number. The multiplicative inverse of a number is well defined to be such that a number multiplied by its multiplicative inverse equals the multiplicative identity value, which is 1. There is no number that can be multiplied by zero to get a value of 1, however, so "dividing by zero" is like trying to multiply by a number that doesn't exist in the first place.
File under 'M' for 'Manic ranting'
It is far better to throw an error than to do something massively stupid.
If your code has anything to do with moving actual physical objects, be it photons or electrons or larger things such as aircraft or spacecraft, your divide by zero errors should be caught and replaced with either an error or if possible with a sensible result. In my experience, with physical things these sensible results are generally not zero, but most commonly plus or minus "infinity" (i.e., something as large as possible). It's also common for a divide by zero to be a symptom of some assumption or approximation failing for the case in question, and completely different code branch may be needed to do the right thing.
You're so close, but you missed it.
In the real world when there are no people, this special case is noticed and the division never occurs. That is what the code should do. Check for cases that would cause a divide by 0 error before the error occurs, not come up with some terrible way to swallow up exceptions that are trying to tell you something bad happened.
https://en.wikipedia.org/wiki/James_Anderson_(computer_scientist)#Transreal_arithmetic_and_other_arithmetics
This seems to make a lot of people very angry, but in the same way as we define i for SQRT(-1) and just carry on, this has 0/0 defined as "nullity" and then you can actually do some rather interesting maths.
Yes it's nonsense in the realworld, but hey, when did that stop mathematicians? The perspex machine paper has some more information: http://www.bookofparagon.com/Mathematics/PerspexMachineIX.pdf
Sure, just choose a default for division by zero. I always prefer silent errors where my software just gets the wrong answer over being informed in no uncertain terms when something is wrong. I mean, the important thing is to keep up appearances, maintain the illusion that everything is okay, isn't it?
Comment removed based on user account deletion
*puts 2 apples in the lap of a quadruple amputee*
What can't i do now?
1/4 = 4 pieces, 1/3 = 3 pieces 1/2 = 2 pieces 1/1 = 1 ... logically then in the integer domain 1/0 = 0 pieces.
In the real number (float) domain it's obviously more complicated ...
1/0.5 = 2 pieces, 1/0.333333333 = 3 pieces 1/0.2 = 5 pieces 1/0.1 = 10 ... 8o(
But that is for the specific infinite domain where x approaches zero ....
If you take the stance that any float y where y = 0 is for all practical purposes an integer and apply the rule consistently, I can't see having an issue with any typical application programming scenario. Where "typical" does not include mathematical operations beyond everyday computation for the average business user.
Typically when writing code, if you're dividing by zero, something f***ed up somewhere. You clearly want to know when this happens; making an erroneous state auto-correct to 0 is a recipe for disaster. I deal with enough suppressed errors at work because of people's crappy coding; I don't need more.
Or so Mathworld tells me, http://reference.wolfram.com/l... because x/0 is a Complex Infinity, therefore the answer must symbolic, NaN and so the answer to your question is that, the harm is that your code could be non-deterministic if you do not define what the outcome should be in each case. i.e. Assumptions are dangerous.
I would typically want div by zero to be equivalent to dividing by the smallest representable possible float. The result of the division would generally be the largest representable float. That's a long way by zero
System wide setting? Most other programs don't want it. What you want is a function you can call at the start of your program: no_div_by_zero_exceptions_in_this_program().
But, that is a bad idea (tm) because the programming language/system doesn't know the context. That is, what you intend if div-by-zero occurs on a line-by-line basis. That's why you have to have explicit checks:
if (y != 0) ...; // what you want: x, 0, inf, -1, throw exception, abort program, whatever
z = x / y;
else
z =
But, this is just a single check out of the things a program has to check for: ...
- null pointers
- array bounds
- insane/wrong values (e.g. a person's age shouldn't be a negative number)
- object in wrong state for operation to be performed (e.g. trying to do a database operation when the DB handle isn't locked)
-
Also, drawing on the recent Linux raid0 problem [where FS corruption was happening], they had something akin to:
sector_offset = absolute_byte_position / sector_size;
If sector_size happened to be zero (a programming mistake), silently returning zero here would corrupt the disk/file.
You've been programming for 20 years? Well, junior [I've been programming for 43--sigh], you've still got a lot to learn. And the fact that you didn't see the harm before you posted proves that.
Like a good neighbor, fsck is there
https://en.wikipedia.org/wiki/...
Indeed. And my programs would run a lot quicker if pi was 4. Does anyone really want pi to be anything other than 4?
For the love of all that's good and pure, please tell me this is a joke.
um....source? I got bored confirming, but if I'm reading you correctly, at least Wikipedia disagrees with you https://en.wikipedia.org/wiki/...
No... the post that RackinFrackin replied to was factually wrong. A number divided by 0 is *NOT* defined as either plus or minus infinity. The definition of division is such that any division by a number is equivalent to multiplying by that number's multiplicative inverse, but 0 does not have such an inverse, so dividing by 0 is like trying to multiply by a number that doesn't even exist.
In other words, it's undefined. Nothing more, and nothing less.
File under 'M' for 'Manic ranting'
Better than Wikipedia maybe take a math course? I mean, if you want to sound like you know anything when discussing math.
Seven puppies were harmed during the making of this post.
"After 20 years of programming..."
Seriously? What language did you program in? HTML4? That's a programming language, right? Just like Pearl and F.O.R.T.R.A.N?
I think I may have come across your resume...
How about "not yet defined". You know, just in case.
Hmm, I've got Khan Academy agreeing with me too: https://www.khanacademy.org/ma... on his board at 3:16. But, what does he know, he's only one of the most highly regarded sources for learning mathematics online...I'm sure it was just a slip-up that no one seems to have successfully countered in his comments...
What a stupid conjecture.
I hate to say it, because I love Being Right On the Internet, but there's already a great explanation of all this malarkey* on the glorious Youtube
https://www.youtube.com/watch?...
and the problem of 0/0 = anything doesn't go away just because a progam finds it in an array operation. It's meaningful.
* here' I'm using malarkey in the proper mathematicly rigorous way
Your bridge falls over.
In "gamer world" a pixel gets maxed out to white.
There is mission critical and then there is graphics.
There is math. Then there is numerical computation. These are 2 totally different things. Learn the difference.
Divide by zero raises a processor exception and dumps core. It has always been such. Learn why.
If you are using C or Fortran on Unix, you have complete control over all of this.
Start Here:
http://www.gnu.org/software/libc/manual/html_node/Floating-Point-Errors.html
Now get the fuck off my lawn.
"Infinity does not exist. Real mathematicians (ie - NOT you) only speak of numbers APPROACHING infinity."
I don't think I count as a real mathematician (but a long time ago in a galaxy far, far away I did get a mathematics degree), so with that caveat:
As someone pointed out above, there is the one-point compactification of the complex plane; also points at infinity in projective geometry, the use of infinite numbers (and infinitesimals) in Non-standard Analysis, and the Surreal numbers, about which Donald Knuth has written a book "Surreal Numbers: How Two Ex-Students Turned on to Pure Mathematics and Found Total Happiness".
In short, that's only the tip of an iceberg of actual infinities. Try searching for: Georg Cantor.
After all, 42 is the answer to life, the universe, and everything. I'm pretty sure that divide by zero falls under the "everything" category.... (grin)
Why can't your floating point unit just return the set of all numbers when you divide by zero? That seems like the right thing to do to me, better than evaluating to 0.
Don't ask me how to encode the set of all numbers, or what a program might do with that once it got that result, probably throw an exception. *wink*
“Common sense is not so common.” — Voltaire
if denominator=0 then return 0;
else return numerator / denominator;
QED.
The concept of nothing only exists in mathematically-based logical structures and death; understanding of "nothing" is prevented by human incomprehension.
You nerds will never find your answer. Peace. *drops mic*
Since 0/0 is undefined, it could just replace it with a random number or a default. In a few limited contexts this might be better than crashing. Of course, that option shouldn't be enabled during development and testing. If this were available, the result would be well-defined: the managers will insist to enable the hide-divide-by-zero, and patch it in the sequel.
Don't waste your vote! Vote for whoever you want, unless you live in a swing state it won't matter anyways
Do everyone a favour and get out of programming. The fact that you ask this boggles the mind. The fact that slashdot would POST this, I just cannot comprehend.
A real, REAL, big W.T.F ????
It depends on exactly what is going on. If its 0/0, then you can assume 0/0 is 0. If its X/0 where X is not zero, then the result is not zero, in fact it tends to want to run off towards infinity. Giving it a value of zero will likely yield very wrong results. If you are calculating Navier-Stokes equations, inflection points might run to zero (causing the entire equation to "blow up" as the result at each inflection point is infinity or at least a very large value). So it all depends on exactly what you are doing.
10/0=10 10/1=5 10/3=1.25
Wanna fight ? Bend over, stick your head up your ass, and fight for air.
Let's round pi down to an even three. Who needs all those silly decimal digits, anyway?
Both of these proposals are absurd beyond belief.
You wouldn't post someone's comment on your web page without escaping it first, would you?
So then when should your code that does division not check that its inputs are valid?
Wh47 d1d j00 541, 31337 15n't t3h r0xor5 ne m0r3???
Why don't we get rid of segmentation faults too when dereferencing the null pointer? What's the harm of just ignoring any program write to unmapped memory, and returning all zeros on a read attempt?
How about an option to make an abort() statement from a library function return 0; instead?
Just do all your calculations in Roman numerals. They didn't have zero in their number system, so you're pretty much good to go.
Jeez, 500+ unhelpful posts... can I get the little green Yahoo Answers checkmark?
If you have 1 apple and no people then no division takes place. The answer is not 0 slices it's "no process completed". The answer is not "no one gets the apple" because there aren't any "ones" in the system to not get the apple, there is no solution other than to scream.
The problem is you don't understand how to properly express the real world in mathematical or algorithmic terms.
Article X: The powers not delegated... by the Constitution...are reserved...to the people
In certain situations, like geometry, it may be appropriate to divide by a number that approaches zero. Due to the limited precision of floating point number, -0.0 and +0.0 can be seen as almost zero. Therefor IEEE defines the result of division by 0.0 to be Infinite (signed appropriately).
I think this mode for floating point calculations is configured by default (I believe that it is a default is specified in the IEEE spec as well) on most CPU bases systems. Other modes include raising an exception/interrupt.
Since integer math does not include infinite it is not possible to define what to do at divide by zero, except for causing an exception/interrupt.
From an engineering point of view having divisions by zero result in infinite is completely valid. But that is because engineers live in a real world of inaccuracies and limits, while mathematicians live in a world of theory where everything is exact.
Now comes the 'however'. Exceptional floating point values, like NaN are handled very slowly on a x86 by both MMX/SSE and the floating point 'co-processor'. I am talking about hundreds of times slower in case of the co-processor, MMX is faster but still slower than normal processing. I am not sure if infinite or denormal numbers (very small values near zero) are part of the special slow-path values.
I remember reading this article years ago in Datamation. http://www.retroarchive.org/cp... Long-winded and filled with marvelously specious arguments.
False.
"The expression 1/0 is not defined either as +INF or INF, because although it is true that whenever f(x) -> 0 for a continuous function f(x) it must be the case that 1/f(x) is eventually contained in every neighborhood of the set {INF, +INF}, it is not true that 1/f(x) must tend to one of these points. An example is f(x) = (sin x)/x (as x goes to infinity). (The modulus |1/f(x)|, nevertheless, does approach +INF.)"
https://en.wikipedia.org/wiki/Extended_real_number_line
We know where leadership by an anti-intellectual "strongman" who scapegoats minorities and likes boisterous rallies goes
There is a system called the extended real number line which does in fact have +INF and -INF as usable values. As you expect, division by zero is still undefined even in that situation.
https://en.wikipedia.org/wiki/Extended_real_number_line
On the other hand, there is an extended complex plane (Reimann sphere) with a single added "point at infinity" for which one can consistently define 1/0 = INF. But this is not the same as any standard computer number format, of course.
https://en.wikipedia.org/wiki/Riemann_sphere
We know where leadership by an anti-intellectual "strongman" who scapegoats minorities and likes boisterous rallies goes
And is the apple still consumed as in the first scenario, or does it need to be treated differently afterward?
We know where leadership by an anti-intellectual "strongman" who scapegoats minorities and likes boisterous rallies goes
The definition of division is that it's the inverse of multiplication: a/b = x means x*b = a. For example: 6/3 = 2 because 2*3 = 6.
But saying that 6/0 = 0 means 0*0 = 6. Which is obviously incorrect for any purpose.
We know where leadership by an anti-intellectual "strongman" who scapegoats minorities and likes boisterous rallies goes
As others point out math uses infinity as something that is approached, further computations with it are only meaningful with enough context to get the rate of approach. The rate of approach can then be compared between multiple computed infinity values when they appear in the same equation and may give you a result that is actually usable or just another number approaching infinity. ( This is from memory, didn't have to use math like that in a long time so beware of errors)
Math as done in most programming languages is incapable of giving you a usable value. In math infinity/infinity for example can give you a result as described above, a programming language like python gives me a NaN, as in not a valid number. The infinity values are more an error flag, you cannot use them, since they do not hold context other than that you exceeded the range of representable values in one direction.
The thing is this, the answer to the question 1/0 = x, for instance, must satisfy the equation x * 0 = 1. But we know that for all numbers, a multiplication by zero will always equal zero. Therefore, the equation has no solution.
Additionally, infinity is not actually a number at all, so it can't be the solution to a polynomial of any sort, because the basic requirement of any solution is that it be a number.
Apologies for the slight sarcasm there - but this stuff does come up a lot. 1/0 is not infinity, positive or negative. Sorry.
If you get such an error it indicates a very fundamental problem wit the logic of the program.
Indeed, there is a very fundamental problem with wit.
This is not an Algebra problem. It's a computer science question really.
When you go over the max in a register and add a number, it folds over. (65536 + 1 = -65535)
This only happens in computers and not in real math. So we need a flag for it and we know we call it the carry flag.
So x/0 is infinite, at least when you approach /0. You cannot make it the max of a datatype or register, so you need another flag. I think its just what this flag is called that is bothering you, or how most code chooses to handle it, not the fact that there is a flag for it at all.
I'd just replace the "DIV ERROR" assert with just a flag that shows the infinity sign (and never ever use it in real production anywhere).
Does that work?
Before asking wikipedia to take a math course, I suggest you read this wikipedia article, which aligns with the math courses I took: https://en.wikipedia.org/wiki/....
0/0, x/0 and -x/0 should be classified as three separate items:
0/0 should result in a value of 0
x/0 (where x is positive and greater than 0) should result in the highest positive value the computer running the calculation can generate.
-x/0 (where x is negative and less than 0) should result in the lowest negative value the computer running the calculation can generate.
-joe the machine
For integer division, just say
inline int div(int a, int b) {
return (a&-!b)/(b|!b);
}
Then use div(x, y) to your heart's content.
I have only had code die with a "divide by zero" exception on a few occasions. In each case, close examination found a logic error in my code that was important to address.
In general, a division by zero error indicates that you are either attacking the problem in the wrong way or are failing to check some boundary condition. Papering over the problem by just setting the answer to zero will leave these logic errors unfixed and cause far worse problems down the line.
In most cases, checking the denominator to make sure that it is not zero is not actually the best approach. Better is to make sure that your code is written so that there will never be a zero there in the first place.
I want to be sure to avoid it at all costs.
Do something else before somebody gets hurt by your ignorance
I have half a dozen identical anecdote from the time i coached a few people in programming language. It is almost as if there was a block hindering the person to realize that there was no way you could divide by zero. It was not that the fact that there was an error was misunderstood, it was the division by zero which seemed not to be understood. I never had so many problem coaching people with other errors.
C. Sagan : A demon haunted world:
http://www.amazon.com/gp/product/0345409469/
visit randi.org
Nope, you can't do that, because there's a continuity fault.
Infinitessimally less than zero (0-) or infinitessimally more than zero (0+) are both scalar values in the same region of continuity around zero, and they have no scalar separation from it (ie. they're both at zero). In contrast, N/(0-) and N/(0+) are not in the same region of continuity at all, but are two points infinitely far apart along this scalar dimension.
In other words, N/0 does not have a properly defined value with scalar continuity. It's more akin to the expression having TWO values simultaneously, which of course is nonsense in a scalar context. That's why you should never even attempt to evaluate N/0, even if your arithmetic representation had a symbol for infinity. The result is not infinity, it's simply ill-formed.
Of course, you need to get down to assembly to mess with this setting, since most programming languages specify a behavior in this case, or behave in an unspecificed way.
Then again, dividing by zero usually means that there's something wrong with your design.
Let me apply for a mortgage with you company. I'll take a zero term year please. Now what will my repayment be?
you may want to program on Arm v8, its assembly instructions do not cause divide by zero hardware exceptions, and division by zero simply writes zero into the destination register.
Why on earth would x/0 be 0?
With GCC, x / 0 == inf, except for 0 / 0 == NaN.
I was quite surprised to discover this when as a teenager I was writing a 2.5D (doom style) game. I was looking for a crash bug, and it occurred to be that I had an y/x, with x,y being the view vector. When looking along the Y axis, that would be 0,1, giving 1/0. Turned out that 1/0 gave inf, and the next step then became arctan(inf), which is 90 degrees.
So, by having X / 0 == inf, (and -X / 0 == -inf), the correct result comes out in the end.
x / 0 == 0 would give wrong results in basically all cases.
I would just like to congratulate everyone on the quality of the replies.
With currently 644 comments and much utilisation of the words 'then' and 'than', everyone has managed to use them correctly.
644/0 = a beautiful day (Friday too).
Validating external data is Programming 101. If you receive a value that cannot be zero, and you cannot absolutely trust the source, then you must check. Data validation is tiresome, but it's part of life.
Defining the result to be zero is incorrect, and will introduce an unknowable number of follow-on problems.
For those who may not be aware, when working with floating point values (as opposed to integers), division by zero is just fine. The IEEE standard defines the answer as infinity, which is a valid value. In some applications, this is a perfectly fine result.
Enjoy life! This is not a dress rehearsal.
How about a simpler approach?
Division is defined as identifying which quotient, multiplied by the divisor, gives the dividend. So, if D / d = q, then q is defined as the number that can be multiplied by d to get D. e.g., 8 / 2 = 3, and the reason why 3 is the correct answer is because 3 times 2 = 8.
Now, using that definition, if we had 8 / 0 = x, please tell me what value of x can be multiplied by zero to get eight.
Oh, there is no such value? Okay, apparently such a value for x is not possible. Similarly, 9 / 0 = x has the same problem, and so does 7 / 0 = x. The pattern here is that we cannot come up with a valid answer to division problems when the divisor is zero.
Now, on the other hand, if we have 0 / 2 = x, we can say that answer (x) is zero, because then x times 2 gives us the desired original number. So the only place that zero is not allowed is in the divisor (the middle number, with the way I've been writing things out).
I am surprised that you are still employed if you are having trouble with trivial mistakes after 20 years of programming. Surely you don't program professionally?
While you are at it, why not just make the computer ignore all of your programming and arithmetic errors, and continue executing your buggy code, and lets also get rid of floating point calculations and do everything with integers. All these fractions are close enough to whole numbers for it not to matter. Yes, you are a really smart cookie with this proposal.
I'm sure with your level of genius, you will now go and implement a floating point exception handler for your programs that implements your revolutionary laws of arithmetic. Good luck.
How is this a real post?
As long as you're proposing such mathematically bogus simplifications, why not define x/y = 0 for ALL values of x and y? That would make just as much sense, and really let you simplify your code even more!
There appears to be some serious peer-reviewed work on this:
http://www.sciencedirect.com/science/article/pii/S0304397508008967
From their conclusion:
"The theory of meadows depends upon the formal idea of a total inverse operator. We do not claim that division by zero
is possible in numerical calculations involving the rationals or reals. But we do claim that zero totalized division is logically,
algebraically and computationally useful: for some applications, allowing zero totalized division in formal calculations,
based on equations and rewriting, is appropriate because it is conceptually and technically simpler than the conventional
concept of partial division."
potential div by zero is reasonable in nav calculations, which is one reason why the complexities of dealing with it are hidden inside the atan2(y,x) function. Both x and y can legitimately go to zero but the function returns +/-pi/2 when y!=0 and x==0. Other cases are matrix operations where it makes sense to check for absurdly small values & replace them by e.g 1e-12 (or whatever is appropriate to the problem) to make the calculations stable.
Your assumption is simply wrong. It can only be expressed as "not a number" and your code should catch this.
There are all sorts of examples to show how allowing div by zero leads to any desired numerical result and not necessarily zero or infinity. My fave is sin(1/x)/x.
First note that f(x) = sin(1/x) is bounded by +1 and -1 but as x -> zero there is not even a limit. The sin frequency increases but it never tends towards any single value. Simple and wonderful.
Now try [sin(1/x)]/x, which has no upper or lower bounds and no limit as x -> zero. Beautiful.
Given your desire to simplify things, this function shows that setting div by zero to ANY number is as good as zero or max or any value you like. The logical conclusion is that any result with a div by zero in it is meaningless.
Coding calculations is very much about handling exceptions, such as div by zero, and controlling floating point accuracy. If you don't like dealing with what is required and if you don't understand why then perhaps you should leave the math to others. Seriously.
BTW, google will graph these functions for you... just enter "plot sin(1/x)/x" into the search dialogue.
endless frabjousity
The question is so stupid that the only reasonable explanation I can find for posting it is that it is just trolling.
Only somebody truly incompetent with regards to the question could advocate such a dysfunctional and dangerous behavior that violates all mathematical rules and expectations. In addition, this person did not even do basic research: For float, such a value already exists, it is called +inf or -inf (dependent of the sign of what you divided) and it is specified in IEEE754.
I nominate this suggestion "most stupid of the month" and the submitter "don't hire, dangerously clueless".
Most ACs are not even worth the keystrokes to insult them. Be generically insulted by this and ignored otherwise.
Compilers and interpreters have been far too lazy for too long.. It is high time they start doing what we mean, not what we say.
For instance non-addressable memory access could be quietly replaced with the previous memory access. Memory contents flagged as string could be used in any arithmetic using any base because the result is coerced into int 1, so as to always succeed. Recursive loops should just break out at some point so we can keep moving along into... umm, some other code? (-- seems reasonable).
Although, I am starting to think that anyone who means for things like that to happen is surely a dick.
I think you underestimate just how much I just dont care.
That's like saying, "after 20 years of programming, your programs should not have bugs." That's just silly and wrong.
Except that, like NaN (Not a Number), INF propagates meaningfully. Once you get an INF all future calculations using that number can only result in INF or NaN (or possibly 0 after dividing a normal number by INF, depending on the implementation. But that's probably okay).
MAX_INT/MIN_INT do not share that property, they're perfectly normal numbers at the limits of representation. The only sign you get of an error is that you have inconsistent data. If you have an INF or NaN showing up in your results it's pretty obvious that there's an error somewhere. MAX_INT though - do a little math on it and it will no longer be obvious that there was ever an error, especially if your valid data may be approaching the limits of your integer range.
Some specific failure cases:
+INF / +INF = NaN ----- MAX_INT / MAX_INT = 1 (You've just performed an undefined operation that completely removes any ability to make a reasonable approximation, where's the warning?)
+INF * 0 = NaN ----- MAX_INT*0 = 0 (same problem, you've done something that can't even be approximated, and it just disappears?!?)
0.0 / 0.0 = NaN ----- 0 / 0 = ??? (again, a completely undefined operation, what should you do?)
+INF / 7 = +INF ----- MAX_INT / 7 = some perfectly normal number (really!?!)
+INF + 1 = +INF ----- MAX_INT + 1 = MIN_INT (getting into some pretty esoteric theoretical mathematics to justify that...)
I agree it would be nice if there were a way to represent +INF, -INF, and NaN in integers, but doing so would greatly complicate integer calculations, which are extremely straightforward in silicon (well, division is a *little* complicated, but not remotely as complicated as floating point addition). And without silicon-level support you'd need to add branching conditionals to EVERY integer calculation, completely killing performance, as well as disrupting lots of traditional integer exploits such as rollover, bitwise operations, and others that are widely deployed as dramatically performance-boosting hacks.
--- Most topics have many sides worth arguing, allow me to take one opposite you.
Please check the appropriate:
[ ] neither have I any idea what math is about, nor do I care about clean programming
[ ] what could go wrong?
[ ] I decided to select "0" as result, because I have no idea how to code the rotated "8" that shows up in them mathy books
[ ] I'm completely and utterly lazy.
Mathematicians sure are tired of checking for div by 0 for hundreds of years now. Yet they know better than to give in to their primal urges, bc they know what havoc any workaround will wreck in the long run. So do your homework. The needs of the many outweigh the needs of the few.
It is not the correct answer since the correct answer is NaN. It's just a hack to avoid having to write exception handlers for every other line of FP code.
If we had to do tons of integer division, we would need an integer NaN too.
Why does the submitter suggest "zero" as the output for division by zero? How is that a better answer than 23?
I am pretty happy with the "this is a fatal error don't do it" approach, but if it has to be a number, why on earth would you pick zero? That is the least plausible outcome.
My blog: http://www.seebs.net/log/ --- My iPhone/iPad app: http://www.seebs.net/seebsfrac/
I'm murky on the details, but Common Lisp's "condition" system might help. It's a generalization of exceptions in that you can raise a condition (which is like throwing an exception) and have the handler specify how to continue the bad computation. So you could set a system-wide handler that catches division by zero and declares the result to be zero, and then your program can continue.
I'm not saying this is necessarily a good idea, but in general, if your question starts with "the programming languages I know don't allow me to do X", then the answer is "Common Lisp".
Infinity does not exist.
I'm sure you can provide some sort of proof for that. While you are at it you can dig up the proof that time continuous.
Real mathematicians (ie - NOT you) only speak of numbers APPROACHING infinity.
Something tells me you don't belong to that group either.
Comment removed based on user account deletion
I work as a mathematical epidemiologist, modelling disease spread in populations. In my work there are three cases when I encounter divide by zero.
1) Disease transmission. Say you have two types of individual, susceptible and infectious, the numbers of which are given by S(t) and I(t), and the total population size is N=S+I. Diseases typically transmits at a rate beta*S*I/N, where beta is the transmission coefficient. What happens when N=0? In this case we want the transmission rate to also be 0.
2) Poisson distributed random numbers. When events happen randomly at rate lambda, the number of events that occur in a time interval dt is n~Poisson(lambda*dt). When lambda=0, you'd always expect n=0. Strictly speaking the Poisson distribution isn't defined for lambda=0, but the limit as lambda->0 is indeed 0. The GNU Scientific Library, Octave, Matlab, and R all return 0 for Poisson(0), however Julia and Numpy both return an error.
3) Adaptive tau leaping. If you aren't using fixed tau leaping, then you need to work out how big a time step you can safely take, which requires bounding the relative change in a variable. This is done by dividing the variable size by the expected change in that variable, and finding the time step tau, repeating for every variable, and taking the smallest time step you get. In this case, it is entirely possible that the expected time step is zero, say when the population is at equilibrium. This doesn't mean that nothing is happening (you should also check that the variance is bounded), and so here you absolutely need that divide by zero is infinity, and that infinity is greater than any other number you might find.
The first two cases are actually undefined (0/0 is mathematically undefined, since you get different answers depending on how you approach the limit), but the desired outcome is clearly zero. The third case is either 0/0 or x/0, but either way you definitely want to interpret the result as infinity.
In my situation, I just wrote a small function called div0, which I use whenever I expect a divide by zero to occur, and know that I want to interpret that as zero, not infinity.
https://www.youtube.com/watch?v=BRRolKTlF6Q
Thank you for finally explaining division by zero correctly.
How about NaN? Oh wait...
I think of dividing by zero the same as dividing by one because in essence you aren't dividing the original number (X) into anything either way.
Seeing the question I thought there had been a *serious* revelation in mathematics that I hadn't heard about.
nope. slashdice being dumb. oh well.
Arguments from mathematical or physical theories or axioms miss the point.
When writing code we need to understand how our code will behave over it's possible inputs. There's nothing inherently wrong with deciding that in a particular bit of code you're going to ensure that "dividing" by 0 gives you 0 (for example), as long as you know what the consequences are for the behaviour of the programs relying on this.
The reason mathematicians get upset by this is that this is not what is normally understood by division. Division by zero isn't defined. Whatever we do in our programs isn't going to change that
They're not in any kind of state to care how many apples they have got, so you can tell them you gave them two apples and then run away.
All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
20 years of programming, and you think division by zero should be treated as zero? Wow ... I hope I never have the misfortune to encounter any of your software
No, it's you that are factually wrong. Pick a book on intro calculus or floating-point numerics before spreading your ignorance on public forum.
> e know that for all numbers, a multiplication by zero will always equal zero
Not for machine floating point. 0*Inf = NaN, as required by standard IEEE 754
You know, your aplomb is actually quite amazing, given your degree of ignorance. I bet you failed your freshmen calculus.
I just checked the date to see if it is April First.
Unfortunately, it's not.
I work with an OpenVMS operating system as one of my primary job requirements. We upgraded from V.x to 8.1 a few years back, and found out the hard way how many times 40 year old data analysis software could try to divide by zero. The old FORTRAN compiler used on 7.x would default a Div-By-Zero to a value of zero, which is not the best answer, but at least doesn't crash the software used to power a large, expensive, and critical test facility. When you are dealing with measurement data coming from a test article, the results don't always fall into clean buckets, and finding out that an unexpected zero was measured and crashed the system (remember, FORTRAN doesn't have a good syntax for try and catch) at a high energy case was a very big deal.
A lot of time and effort was required to go back through the software written over 40 years to try to mitigate MOST of the issues without a complete rewrite.
In a statically typed language like FORTRAN, replacing a div/0 as a character array ("Div/0" or "NaN") as Matlab or untyped languages would does not work, so the usual workaround is to force any case where there is a div/0 to a ludicrous number that is clear (usually something like 999.999, 987.654, etc...)
If some languages had a default for this that was consistent, at least you could go back an examine the data afterwards to determine what caused the issue (or if, by some stroke of chance the 999.999 was a real answer). The right thing would be to rewrite all of the old software with these pieces of code in them, but there is never budget for that, or time and resources even if the money is there.
I Would rather it equal some impossibly large number to make the error quicker and easier to spot.
IT IS A BUG! Fix your fucking bugs. It seems you are tired of programming. Go work at a McDonalds.
OK, fine. *YOU* tell the IEEE-754 floating-point committee that +/- infinity doesn't exist. I'm sure they'd love to correct the standard to remove representations of those two values.
But instead of a system-wide setting, as you suggest, I would propose an Organization-Wide setting so that by gope policy, all computers in the organization could bet set such that div by zero results in zero! Bravo! (Or maybe a country-wide setting dictated by congress? Or a world wide global setting dictated by congress?)
In addition, I am tired of checking for File Not Found errors. When the file can't be found, why not just reformat the drive and create the file for me automatically!
I'll see your senator, and I'll raise you two judges.
Errors are something you better get handled, but if you're uninspired, you can create your own math system like J. A. D. W. Anderson did on his paper "PERSPEX MACHINE VIII: AXIOMS OF TRANSREAL ARITHMETIC". source: http://www.bookofparagon.com/M...
Some teacher in the UK came up with this new concept:
http://www.bbc.co.uk/berkshire...
probably was discussed on /. already, but too lazy to look it up!
"The hallmark of humanity is the ability to move beyond sensory inputs" - Mary Helen Immordino-Yang
In my case at least, if there is a div0 in there somewhere then it's invariably a mistake that I need to correct. I'd prefer that the compiler or SDK barf on it or warn me. Philosophically, I suppose I'd prefer that the production code barf as well instead of managing to zoom past some bad logic.
After decades years of living, I've decided I'm tired of the uncertainty of what happens when I die. Would there be any serious harm in universal consensus that said being dead equals zero? Maybe it exists already, not sure. But I run into it all the time in every religious person I've worked with. Does anyone want what happens when they die to result in anything other than zero?
As long as you are making up shit, you can make up whatever you want, but it doesn't make it true.
This issue is a bit more complicated than you think.
There are several well known proofs that division by 0 is undefined, such as treating division as multiplication by the multiplicative inverse, much as addition as adding the additive inverse, which I mentioned above. If you are partial to calculus (actually, this is precalc-level stuff), another relatively straightforward proof is to consider the limit of division by some number x as x approaches 0 from the positive side vs division by x as x approaches 0 from the negative side. The two limits both have a magnitude of infinity, but are of opposite sign. This means that there is a discontinuity in division by 0, and because there are no mitigating factors in a division operation that suggests that only one of the limits would actually be correct at that value, mathematically it is undefined. For the case of 0/0, consider that the limit of 0/x as x approaches 0 is quite well defined, being 0, and the limit of x/x as x approaches 0 is also well defined, being 1. However, again there are no mitigating factors that suggest only one of these limits would be correct, so this means that you still have a discontinuity at 0, and in absence of any particular reason to choose one limit over the other at 0, that means that expression is undefined as well.
So no.... I am not factually wrong about this.
File under 'M' for 'Manic ranting'
I've been saying this for years: There's no such thing as "real" zero. It's as abstract as infinity. If you probe the vaccuum of space for anything truly empty, you find virtual particle pairs, because there can't be "nothing". I realize that means that the number of battleships sitting on your hand is not zero, but with quantum probability, I'm demonstrably correct (battleships being abstracts for a group of atoms arranged a certain way).
If you divide by zero, you should get a high random number. I think that's the best a computer could do to rendering reality.
D'oh.... stupid freudian typo... didn't notice until after I had submitted.
What I meant in my first sentence above was this:
File under 'M' for 'Manic ranting'
I've rarely seen such crap posted on /. pretending to be knowledgeable.
If x/0 = some constant, whatever that constant might be whether infinity, zero, 8 or whatever, you get this:
x/0 = c = y/0 therefore x = y for all numbers.
So all numbers are equal and mathematics completely breaks down.
divide by zero is UNDEFINED and in programming languages should trigger an exception or error which should be handled in whatever way is appropriate in that program.
In the free world the media isn't government run; the government is media run.
If x/0 = some constant, whatever that constant might be whether infinity, zero, 8 or whatever, you get this:
x/0 = c = y/0 therefore x = y for all numbers.
So all numbers are equal and mathematics completely breaks down.
In the free world the media isn't government run; the government is media run.
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.
Its even simpler than that
If x/0 = some constant, whatever that constant might be whether infinity, zero, 8 or whatever, you get this:
x/0 = c = y/0 therefore x = y for all numbers.
In the free world the media isn't government run; the government is media run.
Well, I am sorry, but you are factually wrong about this. Your "proofs" show that division by zero may be undefined for some cases, which does not change the fact that it is quite well defined for some other cases. IEEE 754 is quite clear on that too. You may wish to eduacte yourself beyond pre-calc before sounding off.
From a scientific simulation point of view the worst possible outcome of a simulation is a result that looks plausible but is in fact wrong. I'd much prefer my program to halt or crash, so that I can start to look where the bug is.
Yes sometimes its a pain. Say I want to measure the velocity by looking at the time taken to cross some region, and sometimes I have zero length regions. Yes i'll get an error, headdesk and add a suitable check. But it will take knowledge of the problem to work out if I should just not report a velocity for that region, or maybe assume it is the same as the previous one, or average the previous and next. If the expression just returned 0 (or 1 (seen as x/x=1)), and that happened to be within the range of plausible values, then it could take weeks or months to spot the issue.
In C++, the result of division by zero is undefined, so the implementation can do whatever it pleases and be in accordance. Whether it throws an exception, returns 42, or loads your hard drive with kiddie porn and emails the FBI, is not a matter covered by the Standard. Check the documentation for your implementation (it doesn't have to be there, since this is not implementation-defined but undefined), or simply DON'T DO THAT.
"When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
Weird, I didn't know that the Unseen University HAD a CS department.
I always figured Mr. Stibbons was just a Tenured Graduate Student.
Why would I want a incorrect answer?
Assuming 0/0=1 gives you inconsistent outcomes unless you're willing to sacrifice associativity of multiplication and division.
Rounding of floating-point multiplication and integer and floating-point division already sacrifices associativity. See legendary a*a*a*a*a*a question on Stack Overflow.
If you answer that question for me, I'll answer yours.
I can save you even more time dealing with exceptions. I have started writing all of my methods in a pattern as follows:
public void DoSomething (object doItToMe) // Do something here! // No-op
{
try
{
}
catch {
}
}
Now I never have to deal with exceptions of any kind!
division can be defined as: For a given X,Y X/Y = Z is equivalent to Find a Z such that Z*Y = X If Y is 0. then any value of Z works - so any division by 0 has infinitely *many* solutions - 0/0 is different only in that convenient things can happen with regard to limits of functions and stuff like that.
I mean, really. Unless something has fundamentally changed in mathematics since I was in school, dividing a number by zero is *undefined*. It doesn't make sense.
If your code is generating divide by zero errors, then you are doing something wrong. Period.
If you are so lazy or intellectually bankrupt that you can't handle that, then you shouldn't be programming computers.
OK, as a programmer who frequently has to test for 0 before dividing because he also frequently forgets and discovers stupid bugs.... I would LOVE it if there was a default value, or several.
The stuff I'm working with now has a lot of math and a lot of division, and mostly the values are all between 0 and 1 or -1 and 1. Quite a lot of the stuff I use does divide one of these variables by another. I have to check for 0 all the time, and it's always obvious to me what the value should be in that circumstance, so I make an if statement to take care of it. It will be a continuous plot basically, of values from 0 to 1 doing other stuff with values from 0 to 1, and I will always hit those boundaries at some point.
So this makes me want specific operators that would produce certain default values when dividing by zero. Like a "/0" operator that means replace with 0 if it's any kind of infinity or not-a-number (or /1, etc.). It seems like this would not be that hard to do in the floating point hardware, giving multiple ways to divide, each with its own boundary conditions and defaults. Hell, it might exist already. The last time I knew most of my computer's opcodes was in about '98. :)
The problem here is that many familiar languages treat try as a statement, not an expression, so you can't catch in a sub-expression and produce a result that continues the expression's evaluation.
Another way of putting it: How should the result of a map() function represent exceptions? If you're not familiar with it, map() takes a callback function and a sequence (such as a list), calls the callback function on each element of the sequence, and returns a new sequence of the function's return values. For example, map(toupper, "Hello world") would produce something analogous to "HELLO WORLD". But if the callback function can throw, how would map() handle cases where some calls throw and others do not?
I'm surprised no one has mentioned this yet, but allowing that x/x can be simplified is dangerous ground because it allows us to prove equalities that are not true. (From another standpoint, then, we can prove by contradiction that x/x does not work for x=0.) For reference, consider the following site about the proof that 1=2. https://www.math.toronto.edu/m...
I'm surprised no one has mentioned this yet, but allowing that x/x can be simplified when x=0 allows for strange equalities to emerge, basically that 0=1 or that 1=2. (This also serves as a proof by contradiction to the ability to simplify x/x for x=0) Consider the following reference: https://www.math.toronto.edu/m...
Pfft. Just draw a line from negative infinity to positive infinity. Where does it cross the x axis? At 0.
If 1/0 = infinity then 0 * infinity = 1 and
2/0 = infinity then 0 * infinity = 2 etc ad nauseum through all the numbers
What is wrong with this (algebraic) picture?
Division by 0 isn't allowed and the programmer needs to decide what the action should be. Do you indicate that the input is invalid? Do you display nothing for result and and results derived from the division by 0? There should be no default. Don't be lazy.
File under 'M' for 'Manic ranting'
Or VB with on error resume next
IEEE floating point has NAN. I have always liked it. 0/0 gives it as a result. Calculating a value and seeing that the result is NAN is often cleaner code then checking each variable for zero first. It would be nice if integral arithmetic had something similar but it is not going to happen.
I propose this solution, in the castle of math it just means switching a couple of different special cases, nothing more. But it certainly makes more sense. You are multiplying or dividing by a non quantity, thus you are not performing the operation and your X remains the same. Simple as pie. Another example of math confusion is including 2 in the prime number sequence. It's a mistake performed only to abide to preexisting dogmas. 2 is clearly an even number, the correct sequence is 1,2,3,5... etc. /end rant
I use 0/0 to create an interrupt which stops execution.
I mean, it's gonna take me awhile to finish drawing this infinitely long line, but so far, it is touching the x access at every single point within the the set of real numbers.
The fact remains, however, that defining 0/0 or 0^0 as 1 is useful in more cases than not 1. See the short explanation or the long explanation.
People will get all stuck on what is mathematically correct. They are missing the point. The point is what happens in my program and for that we need to go to the parent of math. Mathematics are a system of logical abstraction. If I have two coconuts and take one away I have 2 coconuts, logically the same must be true of apples or oranges or fingers and therefore I can predict results using my fingers.
Here is my hypothesis. Anything divided by itself is one. Anything divided by one is itself. Anything divided by nothing has not been divided at all and therefore is unchanged. In kind, the reverse is true, anything multiplied by 0 has not been multiplied and therefore is unchanged. Let's look and see.
Multiplication is addition. Division is subtraction. Let's start with multiplication and show the addition.
2*2 = 4
0+2+2 = 4
Why the zero? Because the second number in multiplication is shorthand for a sequence of +x repetitions. Since this is our first operation, the zero represents the value we had prior to the first operation.
2*1 = 2
0 + 2 = 2
2*0 = 0
0 = 0
As I mentioned above. Prior to the operation we had a value of zero, now we still do.
What about 0*2*3?
This is two operations.
0*2*3 = 0
0+0+0 = 0 (first zero is the starting value)
0*3
0+0+0+0 = 0
What about 2*3*0? Does it break things due to a starting value?
Again, two operations.
0+2+2+2 = 6
6*0 = 0
0 = 0
Still no. Every sequence of multiplications is broken into individual multiplications and the starting value is ALWAYS 0.
Now for division. In division we do something different. We are chopping something up into slices. Whereas multiplication is an operation that always starts with 0. Division is an operation that can start with anything.
6/2 = 3 pieces of 2
6/1 = 6 pieces of 1
6/0 = 6
6/1 and 6/0 may give the same result but there IS a difference. Let's say we have a pile of skittles and I counted them by 1's. I've pulled 6 skittles out, one by one, and ended with a pile of 6 skittles. That is 6/1. Now let's say we have a pile of 6 skittles and don't pull any out. That's 6/0.
Multiplication is a repeated sequence of additions, zero either means you are adding nothing or that the number of additions to make is 0, thereby leaving something untouched those are two different things but both result in 0. Division is taking something and splitting it apart. 0 either means you are starting with nothing or you are indicating not to divide it at all. Thus 0/0 = 0 and 0 * 0 = 0.
Just my 2 cents.
... you need to get out of programming.
Courtesy of the logic of GLADOS...
1. You have a cake.
2. You have to divide the cake to serve it.
3. Count the number of humans that will get cake. (set to 0)
4. Divide the cake into equal slices for each human.
Conclusion: The cake is a lie. Q. E. D.
Div/0 will always be "a lie", because even if you do substitute an infinite value (the closest "irrational" answer) and return a result, the function becomes useless. Infinity is symbolic, it doesn't actually exist, because there's no rational way to express it, let alone apply it to a process. It's an endpoint, not a step.
tl;dr -- Stop using such reckless floating-point math and improve your exception handlers. (maybe even validate input... I know; shocking.) It's not that difficult when (or if) you plan your projects in advance.
Either that, or write your own function for division that traps div/0 and returns a zero for you, then substitute it in for every '/' in your code. Good luck debugging that.
This post © Copyrite Duggeek, all rights reversed.
This question shows why we don't want English majors cross-training into programming. :-)
"There is no god but allah" - well, they got it half right.
And THIS is what keeps you up at night?
I've decided I'm tired of checking for div by zero.
Oh come on, it's not that difficult, pick a default value (say zero) and use it in your own code.
IF X not equal 0 THEN Y=Z/X ELSE Y=0
subject says it all
I'm not even happy with the inaccuracy from converting integer math to floating point.
http://ta.twi.tudelft.nl/users/vuik/wi211/disasters.html
Star Trek transporters are just 3d printers.
Math is not expressive enough to handle the real world, since division by zero can occur without causing a problem. Example: you want to divide apples among people. You have one apple and two people, each person gets half an apple. You have one apple and no people, no one gets the apple. In the real world there is no problem with this reasoning, it's only that math fails to handle it so you have to include extra code to make it come out. In a real life situation, you need no extra error-handling because there is no error. In conclusion, math fails to express the natural world.
Let's deliver one apple for each infinitesimal fraction of a person. (Having fractional people instead of integers here is not unrealistic; say a government declares a law that apples are to be distributed to the population such that there is one apple given for each tenth of a person). Then each person gets a really huge number of apples. Let's deliver one apple for each 2 infinitesimal fractions of a person; now each person gets half as many apples. 3 fractions, 1/3 of that huge number, etc. Hey, let's go the other way, from one apple per 1 fraction to 1 apple per zero; we know what the curve we've just plotted suggests. but you're saying it should be zero? no thanks, I prefer my math without arbitrary discontinuities and singularities.
Star Trek transporters are just 3d printers.
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.
But +0 = -0 ; yet 1/(+0) does not equal 1/(-0) ... Omigod everything we know is wrong. AAAAAAAAHHHHHHH! Does not compute! Danger Will Robinson, Danger! Fzzt! (Thud)
Star Trek transporters are just 3d printers.
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?
If infinity does not exist, for mathematicians, then how many integers are there? And how many points exist between 1.0001 and 1.0002 on the number line?
Star Trek transporters are just 3d printers.
The issue is your type system sucks. What you want are types that guarantee they are non-zero.
So what you want is a type "divisor double" or "divisor integer" where putting a 0 in such a variable generates a type error.
A more sane approach to ignoring the type avoid the error checking you want would be to have this defined using the maybe Monad. Then you could just define
div' takes 2 numbers of types A and returns a Maybe A where
div' x y = if y != 0
then Just (div x y)
else Nothing
Programs then automatically lift
if f takes type B to type C then
f' from Maybe B to Maybe C becomes
f' Just (b) = Just (f b)
f' Nothing = Nothing
etc... Then you get rid of the division by 0 when it makes sense. If you want to cast Nothing to 0 (which I think is dangerous) do it explicitly at some point where you don't want a Maybe object but insist on a base object. You can't change math, but at least it makes the call explicit.
Then let me rephrase in a language that isn't Haskell.
How should the result of Python [some_expression_involving_x for x in some_sequence] represent both values of the expression and exceptions raised during other evaluations of the expression? For example, in a CSV processing, I'm tempted to use [headings.index(x) for x in wanted_cols], but that brings down the whole sequence if even one element of wanted_cols is not present in headings.
That would make debugging much more difficult! While defensive programming is good, being too defensive and not even letting the programmer know when something terrible happened would make debugging very difficult. Imagine if instead of throwing an IndexOutOfBounds Exception Java just returned the last thing in the list. While the program would run it would probably not return the right result. In general, if you divide by zero you screwed up. You probably don't want zero as an answer and there is probably some underlying bug in your program. It would be much more difficult to find that bug if your program just pretended everything was ok. Whereas if it throws a Nan or whatever you know "Oh this value is zero when it shouldn't be". Maybe in very specific cases you would want to have it just set the result to zero. In games for instance you would want the game to try to continue to work, albeit slightly incorrectly, instead of just dying. But forcibly always setting divide by zero to zero system wide would make debugging much more diffficult!
x * 0 = 0. So divide both sides by 0, and you have x = 0/0, which is nonsense - but reveals something: x * 0 = 0 for all x such that x is a real number. So literally, there could be any answer to the question, "What is 0/0?". This is why it's undefined.
Division by zero is undefined. It is an error if it occurs and should be catched. If you allow division by zero, your math is wrong. You can prove whatever you want. Look:
7 * 0 = 17 * 0
now divide by zero, and you get:
7 = 17 which is clearly false. The solution is to forbid division by zero.
I want a divide-by-zero error that occurs in properly validated data to result in a HCF command being carried out.
Further more, I want people writing code for me to actually understand what they're doing, and to analyse their algorithms so that they check data going in, and trap for errors. Yes, it's time-consuming and difficult. But it's also necessary.
Birds are not dinosaur descendants;birds are dinosaurs, for all useful meanings of "birds", "are" and "dinosaurs"
If in your problem domain it makes sense for 0/0 = 0, then write a function that does that. I think it's fair to say that for most of us, that isn't a good solution. Remind me why you're bothering the world with this again?
1/1 = 1 ...
1/0.1 = 10
1/0.00001 = 10000
1/0 = 0
erm, okay. graph that function and ask yourself, can this be right?
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?
"No one shall expel us from the Paradise that Cantor has created."
-- David Hilbert
I calculate
You check for div by zero
Is that too complicated for you Carl?
Say I'm doing texture mapping of a flat plane parallel to the X axis, where world_Z = k/screen_Y. Above and below the horizon, Z is valid. But at the horizon, Z would be infinity. In this case, defining 1/0 as INT_MAX would produce an acceptable display.
If you are dividing by zero YOU ARE DOING IT WRONG.
Say I'm projecting a floor plane (one parallel to the X-Z axis) onto a screen. For any given Y coordinate on the screen, the distance to this plane along Z is proportional to 1/Y. At the horizon, Y is 0, and the distance becomes infinite. The result of this division thus ought to approximate infinity.
You might as well just ignore bus errors as well.
Plenty of 8-bit microprocessors do just that, leaving the last byte of a load instruction on the bus that the load instruction ends up reading due to capacitance. In one project I've made, I use this open bus behavior to enumerate attached peripherals.
In non-Euclidean taxicab geometry, the perimeter of the set of points of distance 1/2 from a given point does equal 4.
Your code that does division probably does that because division has a meaning, and you need that meaning. Trust me and everyone else here who knows math: the meaning you want does not include the case where you are dividing by zero. Dividing by zero is nonsensical in code and in life. So what went wrong with your program to get a zero into the denominator? That's the issue in your program. Is there a place where you can check user inputs to make sure they aren't insane? Is there a place where you're calculating what is supposed to be a very small number but sometimes it rounds down too low and makes your number zero by accident? Put the check there. Are you measuring or counting something that can legitimately be zero? I bet the division scenario doesn't apply in that case. Check for zero and do what does make sense. Fix your program.
--Jaborandy