Overflow in SML - overflow

I am writing a program in SML that takes as an argument an integer N, but for inputs higher than 537070910 it gives me this error: uncaught exception Overflow [overflow].
Any ideas why?

for inputs higher than 537070910 it gives me this error: uncaught exception Overflow
You would probably have to say what it is in "it gives me this error".
The integer 537070910 itself fits within the 30 bits that Standard ML typically has for an int's magnitude:
- Int.maxInt;
val it = SOME 1073741823 : int option
So perhaps it produces a value above Int.maxInt.
Depending on what SML compiler you're using, you may want to either benefit from 64-bit integers or arbitrary-sized integers in the event that your function is dealing with numbers close to the edge.
(If you revise your question to be more specific, I will revise this answer likewise.)

Related

MIPS input string "2147483648", how to return "error: the input number is two big."

Checking MIPS algorithm overflow
error: .assciiz "error: the input number is two big."
buffer: .space 256
For QtSpim, using syscall #5, input integer, there appears to be no way to detect when user input exceeds the 32-bit signed integer range.  No success/failure error code is returned, and the value returned by the syscall, given whatever the user entered, is simply truncated to 32 bits1.
If you want to do overflow checking, you'll have accept string data (instead of integer data) from the console and parse the string to integer checking for overflow during that parse.
Such a parse involves doing a multiplication by 10 and an addition for each digit, so with one approach both of those arithmetic operations would need to involve overflow checking.
Importantly, the input to the parse would be a string, and the output would both a status and a numeric value, unlike syscall #5, so your program can customize behavior.  The status could indicate success, or failures of various kinds, such as non-digit characters, and overflow.
Other approaches to determining the overflow during parse of string to integer are possible, since we know certain facts about decimal digits, such as at most 9 will be added each digit; since we know that 11 total digits (or more) it will overflow (not counting leading zeros, if present).
For example, an alternative approach is to compute the intermediate parse result in 64-bits, then only when converting to 32 bits, check for match of the 32-bit value with the original 64-bit value (match is ok, non-match is overflow).  Since 64 bits can still overflow, counting of total non-zero digits should also be employed with this approach, where anything over 11 would indicate overflow.
The other popular MIPS simulator MARS presents a different challenge/opportunity on overflow with syscall #5 — it takes an exception on overflow, but this is not like a Java or C# exception that is easily caught and handled, but instead this is a fault that transfers control to the kernel exception handler in supervisor mode.
Doing something useful with that would be a topic of advanced operation system coursework.  For one, once you write your own kernel exception handler, you have to be prepared to handle all possible processor exceptions, not just overflow; for another you have to differentiate between the overflow condition and the others so you can handle them separately; and lastly, there's no predefined interface for telling the overflowing user-mode program using syscall #5, that this has occurred, and what the user-mode program wants to do about it, so you'd have to provide such mechanism.
1  These simulators implement effectively useful but an irregular set of system calls — there appears no attempt made to make a complete or well rounded set of syscall operations.  For example, you can read or print an integer or string from/to the console, but can only read or print strings from files — if you want to use files instead of the console with integers, now you have to write your own int to string and vice versa.

Can overflow occur when a positive number is subtracted from a positive number resulting in a negative number?

I am working with the mips assembly language but am confused on the overflow aspect of arithmetic here.
Say I am subtracting 25 from 20 and end up with -5. Would this result in an overflow?
I understand that with addition if you add 2 positive numbers or 2 negative numbers and the output is the opposite sign then there is overflow but am lost when it comes to subtraction.
Find the examples at the extreme, let's do it in 8 bits signed to make it simple but the same principles holds in 32 bits
minuend: the smallest possible positive (non-negative) number, 0 and
subtrahend: the largest possible number, 127
When we do 0 - 127, the answer is -127 and that indeed fits in 8 bits signed.  There is a borrow.  In any processor the effect of the borrow is to propagate 1's though out the upper bits, making it a negative number of the proper magnitude.
Different processors set flags differently based on this borrow, MIPS doesn't have flags, while x86 will set flags to indicate borrow, and other processors will set the flags to indicate carry.
In 8 bit signed numbers:
minuend: the smallest possible positive (non-negative) number, 0 and
subtrahend: the largest possible number, -128
When we do 0 - -128, the answer should be 128, but that cannot be represented in 8 bit signed format, so this is the example of overflow.  0 - -127 = 127 and that can be represented, so no overflow there.
If we do it in 8 bits unsigned, your example of 25-20 = -5, but -5 cannot be represented in an unsigned format, so this is indeed overflow (or modular arithmetic, if you like that).
Short answer: Yes, as the 32-bit representation of -5 is FFFFFFFB.
Long answer: Depends on what you mean by "overflow".
There's signed overflow, which is when you cross the 7FFFFFFF-80000000 boundary.
And there's unsigned overflow where you cross the FFFFFFFF-00000000 boundary.
For signed arithmetic, signed overflow is undeniably a bad thing (and is considered undefined behavior in C and other languages). However, unsigned overflow is not necessarily a problem. Usually it is, but many procedures rely on it to work.
For example, imagine you have a "frame timer" variable, i.e. a 32-bit counter variable that increments by 1 during an interrupt service routine. This interrupt is tied to a real-time clock running at 60 hertz, so every 1/60th of a second the variable's value increases by 1.
Now, this variable will overflow eventually. But do we really care? No. It just wraps around back to zero again. For our purposes, it's fine, since we really don't need to know that accurately how long our program has been running since it began. We probably have events that occur every n ticks of the timer, but we can just use a bitmask for that. Effectively in this case we're using unsigned overflow to say "if this value equals FFFFFFFF and we're about to add 1 to it, reset it to zero instead." Which thanks to overflow we can easily implement without any additional condition checking.
The reason I bring this up is so that you understand that overflow is not always a bad thing, if it's the unsigned variety. It depends entirely on what your data is intended to represent (which is something you can't explain even to a C compiler.)

Overflow datastructure

Everyone knows about overflow in the programming languages, if it happens program goes to crash. However, it is not clear for me what happens actually with data which get out of the boundary. Could you explain me, saying, giving example on C++ or Java. For example, Integer can save maximum 4 byte, what will happen if one puts data more than 4 byte to Integer. How compiler will identify this undefined behaviour?
what will happen if one puts data more than 4 byte to Integer.
Typically the value will roll-over1, meaning it will jump from one end of its range to another.
This can be seen, even in Windows calculator. Start with the highest possible signed 32-bit value:
Now add one to it:
We overflowed the maximum value of a signed Dword (231-1).
1 - This is a typical result. Some architectures might actually generate an exception on integer overflow, so you shouldn't count on this behavior.
How compiler will identify this undefined behaviour?
The compiler won't identify it. That's the problem. C# can mitigate this with the checked keyword, which checks to make sure that any arithmetic done on an integer will not cause overflow/underflow.

MATLAB script to generate reports of rounding errors in algorithms

I am interested in use or created an script to get error rounding reports in algorithms.
I hope the script or something similar is already done...
I think this would be usefull for digital electronic system design because sometimes it´s neccesary to study how would be the accuracy error depending of the number of decimal places that are considered in the design.
This script would work with 3 elements, the algorithm code, the input, and the output.
This script would show the error line by line of the algorithm code.
It would modify the algorith code with some command like roundn and compare the error of the output.
I would define the error as
Errorrounding = Output(without rounding) - Output round
For instance I have the next algorithm
calculation1 = input*constan1 + constan2 %line 1 of the algorithm
output = exp(calculation1) %line 2 of the algorithm
Where 'input' is the input of n elements vector and 'output' is the output and 'constan1' and 'constan2' are constants.
n is the number of elements of the input vector
So, I would put my algorithm in the script and it generated in a automatic way the next algorithm:
input_round = roundn(input,-1*mdec)
calculation1 = input*constant1+constant2*ones(1,n)
calculation1_round = roundn(calculation1,-1*mdec)
output=exp(calculation1_round)
output_round= roundn(output,-1*mdec)
where mdec is the number of decimal places to consider.
Finally the script give the next message
The rounding error at line 1 is #Errorrounding_calculation1
Where '#Errorrounding' would be the result of the next operation Errorrounding_calculation1 = calculation1 - calculation1_round
The rounding error at line 2 is #Errorrounding_output
Where 'Errorrounding_output' would be the result of the next operation Errorrounding_output = output - output_round
Does anyone know if there is something similar already done, or Matlab provides a solution to deal with some issues related?
Thank you.
First point: I suggest reading What Every Computer Scientist Should Know About Floating-Point Arithmetic by David Goldberg. It should illuminate a lot of issues regarding floating-point computations that will help you understand more of the intricacies of the problem you are considering.
Second point: I think the problem you are considering is a lot more complicated than you realize. You are interested in the error introduced into a calculation due to the reduced precision from rounding. What you don't realize is that these errors will propagate through your computations. Consider your example:
output = input*C1 + C2
If each of the three operands is a double-precision floating-point number, they will each have some round-off error in their precision. A bound on this round-off error can be found using the function EPS, which tells you the distance from one double-precision number to the next largest one. For example, a bound on the relative error of the representation of input will be 0.5*eps(input), or halfway between it and the next largest double-precision number. We can therefore estimate some errors bounds on the three operands as follows:
err_input = 0.5.*eps(input); %# Maximum round-off error for input
err_C1 = 0.5.*eps(C1); %# Maximum round-off error for C1
err_C2 = 0.5.*eps(C2); %# Maximum round-off error for C2
Note that these errors could be positive or negative, since the true number may have been rounded up or down to represent it as a double-precision value. Now, notice what happens when we estimate the true value of the operands before they were rounded-off by adding these errors to them, then perform the calculation for output:
output = (input+err_input)*(C1+err_C1) + C2+err_C2
%# ...and after reordering terms
output = input*C1 + C2 + err_input*C1 + err_C1*input + err_input*err_C1 + err_C2
%# ^-----------^ ^-----------------------------------------------------^
%# | |
%# rounded computation difference
You can see from this that the precision round-off of the three operands before performing the calculation could change the output we get by as much as difference. In addition, there will be another source of round-off error when the value output is rounded off to represent it as a double-precision value.
So, you can see how it's quite a bit more complicated than you thought to adequately estimate the errors introduced by precision round-off.
This is more of an extended comment than an answer:
I'm voting to close this on the grounds that it isn't a well-formed question. It sort of expresses a hope or wish that there exists some type of program which would be interesting or useful to you. I suggest that you revise the question to, well, to be a question.
You propose to write a Matlab program to analyse the numerical errors in other Matlab programs. I would not use Matlab for this. I'd probably use Mathematica, which offers more sophisticated structural operations on strings (such as program source text), symbolic computation, and arbitrary precision arithmetic. One of the limitations of Matlab for what you propose is that Matlab, like all other computer implementations of real arithmetic, suffers rounding errors. There are other languages which you might choose too.
What you propose is quite difficult, and would probably require a longer answer than most SOers, including this one, would be happy to contemplate writing. Happily for you, other people have written books on the subject, I suggest you start with this one by NJ Higham. You might also want to investigate matters such as interval arithmetic.
Good luck.

VB6: what is likely cause of Overflow error when using strings?

In VB6, what is the likely cause of an Overflow error? I am using strings when it occurs.
Is it RAM, or hard-drive space? Or is it something internal to VB6?
I am going to take a stab in the dark here, some code would help as Hogan said. Typically overflow error occur with string when VB6 things it is dealing with integer or longs in math formulas and the results are too large for a integer or long to hold.
Depending on the nature of your formula you may get away from the problem by forcing the system to use the numbers as floating point by adding a '.0" at the end. Otherwise use the various Cxxx function to explicitly convert the numbers to a type that has a greater range.
The one thing you consider is that floating point are less precise than whole number integers so make sure you don't lose needed precision when you do the conversion.
Another 'stab', since no code is provided ...
The following will produce an overflow error:
Dim x as integer
x = len(longstring) 'longstring over 32,768 characters in length
Would cause an overflow error.
Dim x as long
x = len(longstring) 'longstring over 32,768 characters in length
Works fine.
Another example of an overflow from Microsoft Support here:
EDIT
A more subtle situation that can catch you off guard:
You attempt to use a number in a calculation, and that number is coerced into an integer, but the result is larger than an integer.
Dim x As Long
x = 2000 * 365 ' Error: Overflow
To work around this situation, type the number, like this:
Dim x As Long
x = CLng(2000) * 365

Resources