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?
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.
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.
no, because div by zero is not equal to zero
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
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.
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
"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.
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.
It seems like catching SIGFPE and handling the floating-point/int div-by-zero cases specifically could help you work around this.
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?
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.
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.)
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)
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
But this is posted to Slashdot whose own coders don't even validate the correctness of the code before they make it live. Such laziness really fits in with the Dice.com mentality.
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.
Good thing you're pushing untested code into production, Dice!
Well, you see, they had this divide by zero error ...
Does anyone want their div by zero errors to result in anything other than zero?
Yes.
No.
Maybe.
Yes, according identity relationships, n / n == 1.
But, as I mentioned above, APL is the only language I am aware of that got this correct.
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
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.
Having a default is fine
for creating really really horrible, impossible to find, bugs
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.
There is no problem with having a default
Sure there is! What happens when your program generates the default value? You have a BUG! Not just any old bug, but one that will be REALLY DIFFICULT to track down and REALLY HARD to fix.
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.
There is no correct answer. What you are doing is not just "undefined" but impossible.
Even an infinite number of zeroes can't multiply out to be anything but zero.
So if you can get the answers "zero", "one", and "infinity" - all within the space of a few seconds - for the same question, there is no "correct" answer.
It's like asking what the square root of -1 is. There is no answer that's a valid number in any of the sets of real or integer numbers.
Division is only defined for non-zero denominators. It's as simple as that. Because there is no possible answer for a zero denominator.
just like zeno, you will never actually get anywhere with that answer
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
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.
First issue, x/0 mathematically is infinity, not zero.
Which infinity? There are many.
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.
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!
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.
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.
Which infinity? There are many.
I think this counts as an "understatement"
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.
First issue, x/0 mathematically is infinity, not zero. Plus, you want the same exact result across all applications ever? There are certainly times where zero is appropriate, there are also many times when one would want to have some representation of infinity; yet others where this simply indicates an error of some other sort and zero is a valid result.
Actually, mathematics does not define the result of x/0 (except in the extended complex plane or Reimann sphere, the answer there is complex infinity). I also fail to see when zero is an appropriate answer. If an application is asked to divide by zero, any subsequent result that uses the outcome of that division will not be mathematically valid. Surely one can see that the application should stop the calculation and report to the user.
For definitions of "well-defined" that selectively ignore the definitions that mathematicians use, perhaps.
File under 'M' for 'Manic ranting'
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.
The sixth infinity.
"Our two-party system is like a bowl of shit looking at itself in a mirror." - Lewis Black
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.
Does anyone want their div by zero errors to result in anything other than zero?
Yes.
No.
File not found.
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.
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.
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.
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").
Absolute idiot. Reminds me of a time years ago when I was working at a University computer center. Despite my cultivated angry looks, a student came up to me with a printout and asked "Uh, what does this mean?" I said, "Oh, you want me to read it to you? It says: Error -divide by zero on line 50." I got a blank stare. So after a minute I further said" It means you are trying to divide by zero on line 50 of your code, which of course you can't do." That was responded to with another blank stare. So I said "look, here is line 50. See those two variables that you are multiplying together and then dividing into those other numbers? One of them must be reaching zero. Since you can't divide by zero the computer is trying to tell you that something has gone wrong. Go back, print out the variables inside the loop right before line 50 and see which one reaches zero. Then figure out why it is zero." The student said nothing and wandered away, apparently unhappy that I just didn't write the code for her.
A few days later one of the student operators who worked for me there said to me "Remember that girl that you tried to help with the divide by zero problem? She's getting a B+ in her computer science class." Such is the state of the education system. This was a while ago, but as far as I can tell, and this post indicates, things have no gotten any better.
No, you don't just ignore this problem and you absolutely don't put a system wide rule in effect to ignore the problem. If you get such an error it indicates a very fundamental problem wit the logic of the program. It is not trivial, and in real world situations could be deadly.
And you don't just return the largest system number rather than zero, as some other idiots have suggested. That would be just as wrong and just as dangerous.
And if you are really seeing this error often, I strongly suggest a change in profession to a short order chef.
I'm an American. I love this country and the freedoms that we used to have.
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
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
Honestly, I think I'd prefer having pi defined as three than have division by zero return zero. My answers will at least be in the right domain even if the value is off a bit.:)
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.
Technically, the result in undefined, hence the exception is generated. However, practically speaking, for divisors close to zero but not zero, the result is +/- infinity, which is what happens in floating point code.
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.
I think this is supposed to be spelled, "your an idiot!!"
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.
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.
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
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.
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.
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.
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.
That's (sort of) what NaN (not a number) is for in C/C++, also "NULL" is traditionally used to represent a missing/undefined value in a database.
And did you exchange a walk on part in the war for a lead role in a cage? - Pink Floyd.
Hey, let's not get hasty. Short order chef is a challenging job with lots of details. You can't just default everyone to cheese omelettes when you can't be assed to check the validity of the table ticket. Clearly this guy needs to work on his attention to detail first. Maybe mopper or busser.
There is an answer, but it is not representable exactly except as a special value (NaN for floating point).
So mathematically it is well defined (exept for 0/0), however in many programming languages it is explicitly stated that the results are undefined. What that means is that the implementer of the language is allowed to do whatever they want (because it's undefined).
Also the math does break down when you divide by zero, so while it's not meaningless it does mean that you can't properly use these values. For example:
"X/N * N == X" or "X/N * N/X == 1"
These equations break down when N is 0
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.
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
Sorry, not mathematically well defined, I goofed up there. If you plot the curve of the results from negative divisors to positive, then there is a discontinuity at zero.
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.
I've always seen IEEE 754 floats give NaN for division by zero, which is fine by me.
You get +/- infinity if a non-zero number is divided by zero, with the sign taken from the denominator. You only get NaN (not a number) if you divide zero by zero.
> No, you don't just ignore this problem and you absolutely don't put a system wide
> rule in effect to ignore the problem. If you get such an error it indicates a very
> fundamental problem wit the logic of the program. It is not trivial, and in real world
> situations could be deadly.
First of all I don't object you - you just don't divide by zero cause math. And it is it.
But could you please describe one (or more if you wish) situation in which such behavior could be deadly?
Seriously I briefly thinked about it in this context (programing) and can't think of any serious practical aplication. I know I feel bad about myself about it... but I really don't know.
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.
Airplane autpilot computes speed from GPS timestamp and position, using difference between now and previous measurement, synced to 1 Hz PPS. Leap second hits, autopilot divides by zero, thinks it's not moving, guns the engines, hijinks ensue.
with the sign taken from the denominator
Should of course be "with the sign taken from the numerator".
I'll go to bed now...
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
Indeed. And my programs would run a lot quicker if pi was 4. Does anyone really want pi to be anything other than 4?
well you can always make a class that encapsulates a number type and give it a default number when it approaches zero, like a very very tiny epsilon, but yeah there are systems where even that is not actually a choice, like some small microprocessors with minimun language support
someone said intel made a chip that could finish an infinite loop in 5 minutes, I don't don't think it would be long before they make one that divides by zero and gives you a meaningful result
I don't want the software/firmware to hide this blatant error in self driving cars, aircraft control systems, air traffic control systems, medical devices (including but not limited to medicine delivery and radiation based treatment and diagnosis), automated or remote controlled military weapons, or even the ABS or power train systems of my current car while I'm driving it in heavy traffic at 70 mph or so. And that is just for starters and a few fairly obvious examples. But pretty much any process control system that affect the real world (meaning all of them) could be capable of inflicting dangers if completely out of control. Other examples could range from anything from automated amusement park rides to computerized legal records (unless you think it is a fun and safe thing to have a dozen over eager SWAT yahoos bust down your door and start getting agressive with their automatic weapons because your finger prints came up a match for who they were looking for, a match that was caused by a complete lack of any similarity in the fingerprints and a divide by zero error).
I'm an American. I love this country and the freedoms that we used to have.
See my response to the same question above. Are you by chance a time traveler from the 1800's or earlier? Because I don't see how anyone born since the end of WWII could even ask that question.
I'm an American. I love this country and the freedoms that we used to have.
It's believable that someone could get a B+ in an entry level CS class even without a good understanding of arithmetic. Entry level CS is more about understanding flow control and variables than it is about mathematics.
If she got a B+ in Calculus, that would be concerning. And since all university-level CS programs require Calculus, the student in your story likely never graduated... unless this was a for-profit college, perhaps.
A slashdotter who didn't build his own computer is like a Jedi who didn't build his own lightsaber.
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...
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...
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
File not found. Try sandpaper.
rewriting history since 2109
The problem lies in the inexpressivity of math, not in the student. Division by zero happens naturally and it is math's problem if it can't deal with it. Natural language can deal with it, nature deals with it. Math fails to express nature adequately.
Example: water flows over an area of land and divides itself evenly: so 1 cubic meter of water / 1 square meter of flat land. Now the land erodes and becomes 0 square meters. The water doesn't have to resort to error-handling code, it knows what to do, it flows on. But math gets hung up at the point when the land disappears, your code throws an error, and you have to handle that. But nature doesn't throw any error, it handles division by zero naturally and seamlessly. Again, math fails to describe nature very well.
It is NOT a science - it is a language. (Note String theory has the same issue.)
As such it can be sued to descr4ibe things - both true things and false things. I can easily write 1+1=3, and I can even describe a universe where that is an axiomatic principle. It is not THIS universe, but it is a theoretical one. Another, easier to understand rule like this is setting the the sum of the angles of a triangle = 190 degrees. This does not work in flat space, but if space is curved by gravity, say near a black hole...
Setting x/0 = 0 is a legitimate choice for some issues, but it may cause major problems in others.
I would not advise making this kind of change.
excitingthingstodo.blogspot.com
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
I always write the result of 0/0 to a random location in memory.
“Common sense is not so common.” — Voltaire
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
Did it occur to you that the girl might not understand the mathematical issue of divide by zero? Seems like you told her everything she OBVIOUSLY already knew and intentionally omitted the part that might have actually clued her in. And why? Because "she should already know that because of prerequisite course X"? Doesn't matter what she "should" know if she doesn't, and you did nothing but perpetuate her ignorance and encourage her to learn more about how to succeed in ignorance. Seems to me you could have taken a minute or two and help her learn/relearn, and maybe get a tiny shred of that "maybe I'm not stupid" feeling, but instead you chose to take your frustration and bitterness out on her in the type of cold manipulative way that you knew an instructor could get away with. I think you "should already know" how to treat human beings, and regard it as a prerequisite for being a teacher.
Except this guy apparently was not an instructor. Part of the college experience is learning who not to approach for advice and instruction.
10/0=10 10/1=5 10/3=1.25
Wanna fight ? Bend over, stick your head up your ass, and fight for air.
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?
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
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 major difference here is that in the first scenario the water stops in the sink, while in the second scenario it doesn't (so no division actually occurred). Every scenario you can think of will have this same problem; in your second version the material will have not been consumed, and you'll be in a situation of still needing to deal with it or pass it on, which is totally unlike the first case.
Reflect on why this is literally called an "overflow" error.
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
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.
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/....
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 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
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?
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.
I was waiting for this one...
--- Most topics have many sides worth arguing, allow me to take one opposite you.
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/
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.
They are regions of space-time from which even light isn't fast enough to escape. Einstein's General Theory of Relativity predicts a singularity at the centre of a black hole i.e. a non zero amount of mass is squished into zero volume. This seems impossible so most people think that GR breaks down in such extreme conditions and we need a new quantum theory of gravity.
i.e. the division by zero is an indication that the model is wrong.
All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
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
ARM thinks that this is valid under certain circumstances and provides an appropriate setting in their CPUs (DIV_0_TRAP).
Would they do that if it was completely useless?
Again, math fails to describe nature very well.
Maths is perfectly capable to describe nature. Insofar as we understand nature (physics), our description uses maths. The problem is in crappy programming. No more, no less.
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.
Imagine a cruise control in a car. Let's say that speed is measured (this may be the way it is really done, but it is speculation) by monitoring a point on the wheel and every time it passes the vertical a subroutine runs that calculates the time difference by using the system clock time now and the last time the subroutine ran and then the speed by dividing the circumference of the wheel by the time difference.
If on two runs, the system clock reports the same time, I can think of two possibilities:
- the system clock is broken
- the wheel is rotating so fast that the system clock does not have enough resolution.
Would you prefer the subroutine to report the speed as 0 thereby causing the cruise control to put the pedal to the metal; "really really fast" thereby causing the cruise control to slam on the breaks, or at least cut all power; or "I don't know how fast we are going" thereby causing the cruise control to disengage, perhaps with a warning to the human driver?
All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
I just checked the date to see if it is April First.
Unfortunately, it's not.
Yes. Because other parts of the cruise control algorithm can recognize a speed of zero as a point where the cruise control should not be operating at all and disengage it.
The other options would be:
Report an arbitrary value. This leads to horrible results as the arbitrary value may be below the set speed, but still in a range where the cruise control operates.
Report the maximum value. This may lead to funny results if the programmer did not pay close attention to signed/unsigned datatypes.
Do random stuff, crash, require restart before cruise control can be re-engaged: This doesn't immediately lead to horrible results, but to lots of unhappy customers wondering why their car needs resets/power cycling like their Windows computer does.
I Would rather it equal some impossibly large number to make the error quicker and easier to spot.
Not ignoring the problem could be deadly, too, or at least very costly. It all depends on the application.
Why do you think ARM put a mode in their CPUs where they just return zero on a division by zero? Does ARM leave their CPU design to idiots? I don't think so.
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'
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.
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.
In the free world the media isn't government run; the government is media run.
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.
For all non-zero n, n/n == 1, since 1 is the only X such that n * X == n. If n is zero, any X will work just fine.
It is possible to assign values to the limit of an expression. As n goes to zero, n / n remains 1. Also, as n goes to zero, 2n / n remains 2. With n == zero, though, n == 2n, so the value of a limit resulting in 0/0 depends entirely on how you got to the limit and not what the final expression is. If you just write 0/0, you're not specifying any sort of expression, and so the value could be any number.
You can argue that if you write n/n, and n happens to be zero, the right answer is 1. I'm not sure this is nearly as useful as throwing or returning NaN, but there's a mathematical basis for it. If you write n/m, and both n and m happen to be zero, and n and m have no guaranteed relation to each other (like m == sin(n) or something), there's no good argument for any value.
"When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
Pretty sure that anything divided by zero is an uncountable infinity. You may want it to be 0, but it mathematically isn't.
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.
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.
This is in full accord with the fact that the editors often get things entirely wrong, and we have to have commenters do that work. Slashdot is ALL about the community.
"When you have eliminated the unacceptable, whatever is left, however improbable, must be the truthiness" - Holmes
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.
The problem lies in the inexpressivity of math, not in the student. Division by zero happens naturally and it is math's problem if it can't deal with it. Natural language can deal with it, nature deals with it. Math fails to express nature adequately.
Example: water flows over an area of land and divides itself evenly: so 1 cubic meter of water / 1 square meter of flat land. Now the land erodes and becomes 0 square meters. The water doesn't have to resort to error-handling code, it knows what to do, it flows on. But math gets hung up at the point when the land disappears, your code throws an error, and you have to handle that. But nature doesn't throw any error, it handles division by zero naturally and seamlessly. Again, math fails to describe nature very well.
This is some pretty unthinking logic you have going on here. How can land erode away to nothing. Is the Earth a flat plate sitting in space and once it erodes away there is nothing there but a hole? You do realize that underneath the land, there is more land right?
If your land is slowly eroding into a channel, then the area is getting smaller. As it gets very narrow the water divides by a smaller and smaller area of land showing the depth to be getting bigger. Once the channel gets to zero width, there is nowhere for the water to go, so it can't be zero depth or even infinite depth, it is a question that makes no sense. If a channel in the real world got infinitely narrow, it would make more sense in the real world that the water would flow over the land that made up the channel's sides, but that is outside the division equation you stated with. That was dividing to find the depth of the water within the channel, once the channel is gone you have to redefine the equation to use another parcel of land.
And if we go to the example where there is a hole into space through the flat earth, then it also makes no sense as there is no depth to water falling through a hole into nothing. It can't spread out onto land that isn't there.
-- ssoorrrryy,, dduupplleexx sswwiittcchh oonn.. -Quote found on actual fortune cookie.
Just give them the ID10T form and move on to other things.
-- ssoorrrryy,, dduupplleexx sswwiittcchh oonn.. -Quote found on actual fortune cookie.
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.
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.
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...
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?
File under 'M' for 'Manic ranting'
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 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.
First issue, x/0 mathematically is infinity, not zero.
That is not quite right.
Division by zero is undefined, or as some say, indeterminate.
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.
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?
In a world gone mad, where pi is (int) 3 and dividing by 0 has a value, terror stalks the halls.
"There is no god but allah" - well, they got it half right.
On a Vax you could dereference a NULL pointer and get zero.
http://www.catb.org/jargon/htm...
Graham
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.
Honestly, I think I'd prefer having pi defined as three than have division by zero return zero. My answers will at least be in the right domain even if the value is off a bit.:)
Pi is three! The Bible does not lie!
1 Kings 7:23
And he made a molten sea, ten cubits from the one brim to the other: it was round all about, and his height was five cubits: and a line of thirty cubits did compass it round about.
It's easy to tell that the 3.14.... number is a Satanic Lie; merely add the first 144 digits. What do you get? 666!!!!!
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.
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"
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?
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.
I don't know why are you hostile? :) If you could describe a situation in which allowing divide by zero would be deadly. I don't disagree with you - I AGREE - YOU DONT DIVIDE BY ZERO - BASIC MATH. But also I wonder how one can explain this to another by example on how it could be deadly (a airplane example, nuclear powerplant maybe)?
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