Arithmetically simulate 32-bit integer overflow - type-conversion

Is there a way to arithmetically simulate 32-bit, twos-complement integer overflow with numbers of a type whose value space is a strict superset of that of the 32-bit twos-complement integers? I need to perform such an operation in, for example, WolframAlpha, which has no explicit typing and no type casting.
The output of my desired convertTo32BitSignedInt(aValue) function needs to be the same as if I had cast the value in a language that supports it, such as Java: (int)aValue.
By example, the output of convertTo32BitSignedInt(17643225600) needs to be 463356416, the same as I had used the following cast (int)17643225600.
For the moment, my convertTo32BitSignedInt function (in pseudo code) looks like this and I am pretty sure it's not the better solution.
if(x > 2147483647 && floor(x / 2147483647 ) == 1){
return (x - 2*2147483648);
}else if(x > 2147483647 && (x % 2147483647 == 0) && (x % 2 == 0)){
return -1 * (x / 2147483647);
}else if(x > 2147483647 && (x % 2147483647 == 0) && (x % 2 > 0)){
return -1 * ((x - 2147483647) / 2147483647) + 2147483647;
}else if(x > 2147483647 && (x % 2147483647 > 0) && (x % 2 == 0)){
return -1 * floor(x / 2147483647) + (x % 2147483647);
}
//...
Use Case:
I try to demonstrate a certain behavior that will occures when there is a 32-bit signed integer overflow in a java program using a recursive implementation of the factorial function.
public int factorial(int n) {
return n == 1 || n==0 ? 1 : n * factorial(n - 1);
}
This int implementation, for factorial(13) gives 1932053504, because 13 * 479001600 > 2147483647, the 32-bit signed integer maximum value.
I use WolframAlpha for the demonstration. WolframAlpha allows numbers > 2147483647 and I want to simulate these number as 32-bit integer numbers. WolframAlpha gives the real answer which is 6227020800. I would like to be able to convert 6227020800 as 1932053504.

Edit: this is a rip & replace of my initial answer
You can do something roughly like this:
convertTo32BitSignedInt(aValue) {
bits32 = BitAnd(aValue, BitShiftLeft(1, 32) - 1);
sign = BitShiftRight(bits32, 31);
return bits32 - BitShiftLeft(sign, 32);
}

Related

How to produce negative Nan?

I have a "creative" algorithm I'm working on, and there is a case where I need to return negative Nan.
extension Decimal {
func placement(
between gains: Decimal,
and losses: Decimal
) -> Decimal {
if gains == losses {
return self > gains ? (1 / 0) : (-1 / 0)
}
return (self - losses) / (gains - losses)
}
}
Unfortunately (-1 / 0) produces Nan instead of -Nan.
I've accidentally created -Nan previously, unfortunately, I don't remember how it happened.
When something is literally "not a number", how can it have a meaningful sign?
And, from a practical perspective, how do you expect to distinguish "negative NaN" from "NaN"? Decimal.nan == -Decimal.nan is true, as well as Decimal.nan < 0 and -Decimal.nan < 0
let n = Decimal.nan
let nn = -Decimal.nan
print (n < 0) // true
print (nn < 0) // true
print (nn < n) // false
print (n < nn) // false
print (n == nn) // true
print(-Double.nan) // produces -nan
print(-Decimal.nan) // produces Nan
I think Decimal might not track signed nan. It doesn't distinguish between positive and negative nan but if it is negative nan, isNan will produce true.

How does a recursive function return the result in scala?

I am currently learning Scala and I am stuck in the following thing:
I have this algorithm which finds in a recursive way the factorial of a number:
def fact(n:Int): Int=
{
if(n == 1) 1
else n * fact(n - 1)
}
println(fact(5))
My question is, why does this line: if(n == 1) 1 does exactly? Does in mean that the function should return one or that n should become 1? I dont understand how this function returns 120 which is the result. Could someone help me udnerstand? I appreciate any help you can provide
Uhm, this is a very broad question.
Since you are asking for basic understanding of the operators of the language. I will try to explain it all to you, but I would recommend you to take a formal introduction to programming course.
In Scala everything is an expression. Thus, the function itself is an expression that evaluates to the assigned block.
In this case the block is just an if / else expression, which takes a predicate to decide which of the two branches to choose. In this case n == 1 checks if n is equals to 1, if that is true, then it returns 1, if not, it returns n * fact(n -1).
Thus, if we execute the algorithm by ourselves using "equational reasoning", we can understand how it works.
fact(3) = if (3 == 1) 1 else 3 * fact(3 - 1) // replace n in the block.
fact(3) = 3 * fact(2) // reduce the if and the subtraction.
fact(3) = 3 * (if (2 == 1) 1 else 2 * fact(2 - 1)) // expand the fact definition.
fact(3) = 3 * (2 * fact(1)) // reduce the if and the subtraction.
fact(3) = 3 * (2 * (if (1 == 1) 1 else 1 * fact(1 - 1))) // expand the fact definition.
fact(3) = 3 * (2 * (1)) // reduce the if.
fact(3) = 6 // reduce the multiplications.
Lets make this method more c oriented.
Maybe now its more clear that there are two branches
1. When n equals 1 - which stops the recursion.
2. Otherwise - multiply the current value of n by the result of calling the fact method with n - 1, which eventually becomes 1 and stops the recursion.
def fact(n:Int): Int=
{
if (n == 1) {
(return) 1;
}
else {
(return) n * fact(n - 1);
}
}
The semicolon is redundant and the the a return keyword is not recommended/necessary.
You can read about it here
So you are left with:
def fact(n:Int): Int=
{
if (n == 1) {
1
}
else {
n * fact(n - 1)
}
}
Which is basically the same as:
def fact(n:Int): Int=
{
if (n == 1) 1;
else n * fact(n - 1)
}

How to check if a number is a power of 2 in SWIFT

I find out a lot of example to solve it, but nothing in SWIFT. Please help
smthng like this
Input : n = 4
Output : Yes
2^2 = 4
Input : n = 7
Output : No
Input : n = 32
Output : Yes
2^5 = 32
I needed algorithm for checking if a number is a power of 2. like 4, 8, 16 , 32 , 64 .... is number power of two
Determining if an integer is a power of 2
from the Bit Twiddling Hacks
is almost verbatim translated to Swift:
func isPowerOfTwo(_ n: Int) -> Bool {
return (n > 0) && (n & (n - 1) == 0)
}
Example:
print(isPowerOfTwo(4)) // true
print(isPowerOfTwo(5)) // false
Or as a generic function, so that it can be used with all binary
integer types:
func isPowerOfTwo<T: BinaryInteger> (_ n: T) -> Bool {
return (n > 0) && (n & (n - 1) == 0)
}
Example:
print(isPowerOfTwo(Int16(4))) // true
print(isPowerOfTwo(UInt8(5))) // false
Or as a protocol extension:
extension BinaryInteger {
var isPowerOfTwo: Bool {
return (self > 0) && (self & (self - 1) == 0)
}
}
Example:
print(1048576.isPowerOfTwo) // true
print(Int(50).isPowerOfTwo) // false
Partial answer:
If it's a FixedWidthInteger and it's positive and its non zero bit count is 1, then it is a power of 2.
let x = 128
if x > 0 && x.nonzeroBitCount == 1
{
// power of 2
}
For a floating point number, I think you can just test the significand. If it is exactly 1, the number is a power of 2.
let x: Double = 4
if x > 0 && x.significand == 1
{
// Power of 2
}
I haven't checked that in a Playground yet, so it might be wrong.
let numberToBeChecked = 4
result = numberToBeChecked.squareRoot()
If result%1 == 0 {
print(“4 is a power of 2”) } else {
print(“4 is not a power of 2”)
}
//note: result%1== 0 checks if result is a whole number.
Hope this works.

Nyquist criterion - undefined variable in algorithm

I write an algorithm that checks the stability of the closed system of the Nyquist criterion (http://en.wikipedia.org/wiki/Nyquist_stability_criterion)
function answear=stability(re,im)
%% Function check stability of system
%re is real part of transmitation
%im is imagine part of transmitation
%% Check number of vectors elements
re(end +1:5) = 0;
im(end +1:5) = 0;
if( length(re) > length(im))
root = length(re);
else
root = length(im);
end
for w=1:root
tran(w) = re(1) + re(2)*w.^1 + re(3)*w.^2 + re(4)*w.^3 + re(5)*w.^4 +1i*(...
im(1) + im(2)*w.^1 + im(3)*w.^2 + im(4)*w.^3 +im(5)*w.^4);
end
%% Algorithm
switch root
case 0
exist('Write nonzero numbers', 'var')
case 1
for w=1:length(w)
if( real(tran(w)) > 0 && imag(tran(w)) > 0)
answear=1;
else
answear=0;
end
end
case 2
for w=1:length(w)
if( real(tran(w)) > 0 && imag(tran(w)) > 0)
if( real(tran(w)) < 0 && imag(tran(w)) > 0)
answear=1;
else
answear=0;
end
end
end
case 3
for w=1:length(w)
if( real(tran(w)) > 0 && imag(tran(w)) > 0)
if( real(tran(w)) < 0 && imag(tran(w)) > 0)
if( real(tran(w)) < 0 && imag(tran(w)) < 0)
answear=1;
else
answear=0;
end
end
end
end
case 4
for w=1:length(w)
if( real(tran(w)) > 0 && imag(tran(w)) > 0)
if( real(tran(w)) < 0 && imag(tran(w)) > 0)
if( real(tran(w)) < 0 && imag(tran(w)) < 0)
if( real(tran(w)) > 0 && imag(tran(w)) < 0)
answear=1;
else
answear=0;
end
end
end
end
end
end
%% Answear
if answear==1
disp('System unstable')
else
disp('System stable')
end
plot(real(tran),imag(tran))
grid on
end
Function returns
Undefined function or variable "answear".
Error in stability (line 87) if answear==1
So the algorithm is badly written?
Your code could use a lot of cleanup:
Instead of an if-statement such as this one:
if( real(tran(w)) > 0 && imag(tran(w)) > 0)
answear=1;
else
answear=0;
end
you could write a boolean assignment:
answear = real(tran(w)) > 0 & imag(tran(w)) > 0);
Why do you have three (almost) identical nested if-statements at all?
if( real(tran(w)) > 0 && imag(tran(w)) > 0)
if( real(tran(w)) < 0 && imag(tran(w)) > 0)
if( real(tran(w)) < 0 && imag(tran(w)) < 0)
First of all, you could replace everything with one if-statement. But what are you actually testing with this? It seems that those nested if statements are never executed. For instance, real(tran(w)) cannot be both positive and negative at the same time (unless it is a vector you are working on, in which case you shouldn't be using the operator &&).
Also, this is probably your code triggers the error regarding variable answear. Accessing it is impossible since it hasn't been assigned a value (none of the if-statements have been executed).
What is tran, and what is w? Are they global variables? If they are, pass them as input parameters. Your function is probably poorly designed if it relies on external states and variables.
I haven't actually run your code, but these suggestions should make it easier for you to debug it.
P.S:
Please fix the annoying spelling error (it is "answer" and not "answear") :)

"Nearly divisible"

I want to check if a floating point value is "nearly" a multiple of 32. E.g. 64.1 is "nearly" divisible by 32, and so is 63.9.
Right now I'm doing this:
#define NEARLY_DIVISIBLE 0.1f
float offset = fmodf( val, 32.0f ) ;
if( offset < NEARLY_DIVISIBLE )
{
// its near from above
}
// if it was 63.9, then the remainder would be large, so add some then and check again
else if( fmodf( val + 2*NEARLY_DIVISIBLE, 32.0f ) < NEARLY_DIVISIBLE )
{
// its near from below
}
Got a better way to do this?
well, you could cut out the second fmodf by just subtracting 32 one more time to get the mod from below.
if( offset < NEARLY_DIVISIBLE )
{
// it's near from above
}
else if( offset-32.0f>-1*NEARLY_DIVISIBLE)
{
// it's near from below
}
In a standard-compliant C implementation, one would use the remainder function instead of fmod:
#define NEARLY_DIVISIBLE 0.1f
float offset = remainderf(val, 32.0f);
if (fabsf(offset) < NEARLY_DIVISIBLE) {
// Stuff
}
If one is on a non-compliant platform (MSVC++, for example), then remainder isn't available, sadly. I think that fastmultiplication's answer is quite reasonable in that case.
You mention that you have to test near-divisibility with 32. The following theory ought to hold true for near-divisibility testing against powers of two:
#define THRESHOLD 0.11
int nearly_divisible(float f) {
// printf(" %f\n", (a - (float)((long) a)));
register long l1, l2;
l1 = (long) (f + THRESHOLD);
l2 = (long) f;
return !(l1 & 31) && (l2 & 31 ? 1 : f - (float) l2 <= THRESHOLD);
}
What we're doing is coercing the float, and float + THRESHOLD to long.
f (long) f (long) (f + THRESHOLD)
63.9 63 64
64 64 64
64.1 64 64
Now we test if (long) f is divisible with 32. Just check the lower five bits, if they are all set to zero, the number is divisible by 32. This leads to a series of false positives: 64.2 to 64.8, when converted to long, are also 64, and would pass the first test. So, we check if the difference between their truncated form and f is less than or equal to THRESHOLD.
This, too, has a problem: f - (float) l2 <= THRESHOLD would hold true for 64 and 64.1, but not for 63.9. So, we add an exception for numbers less than 64 (which, when incremented by THRESHOLD and subsequently coerced to long -- note that the test under discussion has to be inclusive with the first test -- is divisible by 32), by specifying that the lower 5 bits are not zero. This will hold true for 63 (1000000 - 1 == 1 11111).
A combination of these three tests would indicate whether the number is divisible by 32 or not. I hope this is clear, please forgive my weird English.
I just tested the extensibility to other powers of three -- the following program prints numbers between 383.5 and 388.4 that are divisible by 128.
#include <stdio.h>
#define THRESHOLD 0.11
int main(void) {
int nearly_divisible(float);
int i;
float f = 383.5;
for (i=0; i<50; i++) {
printf("%6.1f %s\n", f, (nearly_divisible(f) ? "true" : "false"));
f += 0.1;
}
return 0;
}
int nearly_divisible(float f) {
// printf(" %f\n", (a - (float)((long) a)));
register long l1, l2;
l1 = (long) (f + THRESHOLD);
l2 = (long) f;
return !(l1 & 127) && (l2 & 127 ? 1 : f - (float) l2 <= THRESHOLD);
}
Seems to work well so far!
I think it's right:
bool nearlyDivisible(float num,float div){
float f = num % div;
if(f>div/2.0f){
f=f-div;
}
f=f>0?f:0.0f-f;
return f<0.1f;
}
For what I gather you want to detect if a number is nearly divisible by other, right?
I'd do something like this:
#define NEARLY_DIVISIBLE 0.1f
bool IsNearlyDivisible(float n1, float n2)
{
float remainder = (fmodf(n1, n2) / n2);
remainder = remainder < 0f ? -remainder : remainder;
remainder = remainder > 0.5f ? 1 - remainder : remainder;
return (remainder <= NEARLY_DIVISIBLE);
}
Why wouldn't you just divide by 32, then round and take the difference between the rounded number and the actual result?
Something like (forgive the untested/pseudo code, no time to lookup):
#define NEARLY_DIVISIBLE 0.1f
float result = val / 32.0f;
float nearest_int = nearbyintf(result);
float difference = abs(result - nearest_int);
if( difference < NEARLY_DIVISIBLE )
{
// It's nearly divisible
}
If you still wanted to do checks from above and below, you could remove the abs, and check to see if the difference is >0 or <0.
This is without uing the fmodf twice.
int main(void)
{
#define NEARLY_DIVISIBLE 0.1f
#define DIVISOR 32.0f
#define ARRAY_SIZE 4
double test_var1[ARRAY_SIZE] = {63.9,64.1,65,63.8};
int i = 54;
double rest;
for(i=0;i<ARRAY_SIZE;i++)
{
rest = fmod(test_var1[i] ,DIVISOR);
if(rest < NEARLY_DIVISIBLE)
{
printf("Number %f max %f larger than a factor of the divisor:%f\n",test_var1[i],NEARLY_DIVISIBLE,DIVISOR);
}
else if( -(rest-DIVISOR) < NEARLY_DIVISIBLE)
{
printf("Number %f max %f less than a factor of the divisor:%f\n",test_var1[i],NEARLY_DIVISIBLE,DIVISOR);
}
}
return 0;
}