How to normalize Integer variable to positive negative or zero with bit operations - swift

7 -> 1
0 -> 0
-7 -> -1
I've have code:
(x == 0 ? 0 : x / abs(x)) + 1
but is it possible to avoid division and make it faster?

How about
(x == 0 ? 0 : (x < 0 ? -1 : 1))

The idea was to use bit operations to avoid branching code or value conversion.
Haven't found how to do it with bit operations but apple already add this function
https://developer.apple.com/documentation/swift/int/2886673-signum
signum()
Returns -1 if this value is negative and 1 if it’s positive; otherwise, 0.
so simple) raw test shows ~x100 faster implementation

Related

what formula can identify an ODD vs EVEN number

what formula can identify an ODD vs EVEN number
ODD result can be 0
EVEN result can be 1
or vice versa
The expression:
Mod ( YourNumber ; 2 )
returns 1 (True) if YourNumber is odd, 0 (False) otherwise.
The expression:
not Mod ( YourNumber ; 2 )
returns 1 (True) if YourNumber is even, 0 (False) otherwise.

Swift 3 generic type function to clamp numeric values into 0 and 1 interval

I want to write a function that clamps a numeric value into the closed 0,1 interval:
func clamp01<T:???>(_ value:T) -> T {
return value < 0 ? 0 : value > 1 ? 1 : value
}
In Swift 3 if I use T:Strideable I get a complaint that 0 and 1 must be typecast (0 as! T resolves the issue, but it's a forced cast).
In Swift 4 I may be able to use T:Numeric but I haven't tried that -- I am looking for a solution in Swift 3.
You could define the function for all Comparable types which
are also ExpressibleByIntegerLiteral, that covers all integer
and floating point types:
func clamp01<T: Comparable & ExpressibleByIntegerLiteral>(_ value: T) -> T {
return value < 0 ? 0 : value > 1 ? 1 : value
}

Using the 'not' operator in Boolean statements for Matlab

If a statement like ~(5>4) || (1>10) is given what does it evaluate to in MATLAB?
What I think is the answer is :
~1 || 0 = 0 || 0
= 0
so it evaluates to false.
Am I correct in that the not operator only attaches to the (5 > 4)?
In this case, Matlab would evaluate the logical operators from left to right. See Operator Precedence for instances when this would not be the case.
That would mean that ~(5>4) | (1>10) would first evaluate the left half of the OR:
~(5>4) --> ~(1) --> 0
Then continuing...
0 | (1>10) --> 0 | 0 --> 0

Implementation of correlation matrix in MATLAB

I want to implement the following formula in MATLAB, where u_i^(k) means the i,k element. However, I get different results from the ones I compute by hand... I believe that something is wrong with my MATLAB code. For instance,
I should get:
L_ii =
0.1022 0 0
0 0.1657 0
0 0 2.7321
U_ij =
0.7514 0.3104 0.5823
-0.6513 0.4901 0.5793
-0.1055 -0.8145 0.5704
1,1=1-(0.1022*(+0.7514)^2+0.1657*(+0.3104)^2+2.7321*(+0.5823)^2)=-0.000049
2,2=1-(0.1022*(-0.6513)^2+0.1657*(+0.4901)^2+2.7321*(+0.5793)^2)=-0.000015
3,3=1-(0.1022*(-0.1055)^2+0.1657*(-0.8145)^2+2.7321*(+0.5704)^2)=+0.000030
Any ideas??? Please, help me fix Epsilon first (it might not need to move on Rho. Let's fix Epsilon first...)
EDIT: Here is a sample code:
E_squared_ii = ONES_j - diag(L_ii)' * (U_ij'.^ 2)
And here is the wrong result I get at the moment:
E_squared_ii =
1.0e-15 *
0.444089209850063 0.333066907387547 -0.222044604925031
If I use your values and code, I get the expected result:
>> L_ii
L_ii =
0.1022 0 0
0 0.1657 0
0 0 2.7321
>> U_ij
U_ij =
0.7514 0.3104 0.5823
-0.6513 0.4901 0.5793
-0.1055 -0.8145 0.5704
>> ONES_j
ONES_j =
1 1 1
>> E_squared_ii = ONES_j - diag(L_ii)' * (U_ij'.^ 2)
E_squared_ii =
1.0e-04 *
-0.4935 -0.1451 0.2985
Presumably this means that something isn't the value you think it is...

Why are XOR often used in java hashCode() but another bitwise operators are used rarely?

I often see code like
int hashCode(){
return a^b;
}
Why XOR?
Of all bit-operations XOR has the best bit shuffling properties.
This truth-table explains why:
A B AND
0 0 0
0 1 0
1 0 0
1 1 1
A B OR
0 0 0
0 1 1
1 0 1
1 1 1
A B XOR
0 0 0
0 1 1
1 0 1
1 1 0
As you can see for AND and OR do a poor job at mixing bits.
OR will on average produce 3/4 one-bits. AND on the other hand will produce on average 3/4 null-bits. Only XOR has an even one-bit vs. null-bit distribution. That makes it so valuable for hash-code generation.
Remember that for a hash-code you want to use as much information of the key as possible and get a good distribution of hash-values. If you use AND or OR you'll get numbers that are biased towards either numbers with lots of zeros or numbers with lots of ones.
XOR has the following advantages:
It does not depend on order of computation i.e. a^b = b^a
It does not "waste" bits. If you change even one bit in one of the components, the final value will change.
It is quick, a single cycle on even the most primitive computer.
It preserves uniform distribution. If the two pieces you combine are uniformly distributed so will the combination be. In other words, it does not tend to collapse the range of the digest into a narrower band.
More info here.
XOR operator is reversible, i.e. suppose I have a bit string as 0 0 1 and I XOR it with another bit string 1 1 1, the the output is
0 xor 1 = 1
0 1 = 1
1 1 = 0
Now I can again xor the 1st string with the result to get the 2nd string. i.e.
0 1 = 1
0 1 = 1
1 0 = 1
So, that makes the 2nd string a key. This behavior is not found with other bit operator
Please see this for more info --> Why is XOR used on Cryptography?
There is another use case: objects in which (some) fields must be compared without regarding their order. For example, if you want a pair (a, b) be always equal to the pair (b, a).
XOR has the property that a ^ b = b ^ a, so it can be used in hash function in such cases.
Examples: (full code here)
definition:
final class Connection {
public final int A;
public final int B;
// some code omitted
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Connection that = (Connection) o;
return (A == that.A && B == that.B || A == that.B && B == that.A);
}
#Override
public int hashCode() {
return A ^ B;
}
// some code omitted
}
usage:
HashSet<Connection> s = new HashSet<>();
s.add(new Connection(1, 3));
s.add(new Connection(2, 3));
s.add(new Connection(3, 2));
s.add(new Connection(1, 3));
s.add(new Connection(2, 1));
s.remove(new Connection(1, 2));
for (Connection x : s) {
System.out.println(x);
}
// output:
// Connection{A=2, B=3}
// Connection{A=1, B=3}