Strange behavior in a simple for using uint - actionscript-3

This works as expected:
for (var i:uint = 5; i >= 1; i-- )
{
trace(i); // output is from 5~1, as expected
}
This is the strange behavior:
for (var i:uint = 5; i >= 0; i-- )
{
trace(i)
}
// output:
5
4
3
2
1
0
4294967295
4294967294
4294967293
...
Below 0, something like a MAX_INT appears and it goes on decrementing forever. Why is this happening?
EDIT
I tested a similar code using C++, with a unsigned int and I have the same result. Probably the condition is being evaluated after the decrement.

The behavior you are describing has little to do with any programming language. This is true for C, C++, actionscript, etc. Let me say this though, what you do see is quite normal behavior and has to do with the way a number is represented (see the wiki article and read about unsigned integers).
Because you are using an uint (unsigned integer). Which can only be a positive number, the type you are using cannot represent negative numbers so if you take a uint like this:
uint i = 0;
And you reduce 1 from the above
i = i - 1;
In this case i does not represent negative numbers, as it is unsigned. Then i will display the maximum value of a uint data type.
Your edit that you posted above,
"...in C++, .. same result..."
Should give you a clue as to why this is happening, it has nothing to do with what language you are using, or when the comparison is done. It has to do with what data type you are using.
As an excercise, fire up that C++ program again and write a program that displays the maximum value of a uint. The program should not display any defined constants :)..it should take you one line of code too!

Related

How to optimize finding values in 2D array in verilog

I need to set up a function that determines if a match exists in a 2D array (index).
My current implementation works, but is creating a large chain of LUTs due to if statements checking each element of the array.
function result_type index_search ( index_type index, logic[7:0] address );
for ( int i=0; i < 8; i++ ) begin
if ( index[i] == address ) begin
result = i;
end
end
Is there a way to check for matches in a more efficient manner?
Not much to be done, really; at least for the code in hand. Since your code targets hardware, to optimize it think in terms of hardware, not function/verilog code.
For a general purpose implementation, without any known data patterns, you'll definitely need (a) N W-bit equality checks, plus (b) an N:1 FPA (Fixed Priority Arbiter, aka priority encoder, aka leading zero detector) that returns the first match, assuming N W-bit inputs. Something like this:
Not much optimization to be done, but here are some possible general-purpose optimizations:
Pipelining, as shown in the figure, if timing is an issue.
Consider an alternative FPA implementation that makes use of 2's complement characteristics and may result to a more LUT-efficient implementation: assign fpa_out = fpa_in & ((~fpa_in)+1); (result in one-hot encoding, not weighted binary, as in your code)
Sticking to one-hot encoding can come in handy and reduce some of your logic down your path, but I cannot say for sure until we see some more code.
This is what the implementation would look like:
logic[N-1:0] addr_eq_idx;
logic[N-1:0] result;
for (genvar i=0; i<N; i++) begin: g_eq_N
// multiple matches may exist in this vector
assign addr_eq_idx[i] = (address == index[i]) ? 1'b1 : 1'b0;
// pipelined version:
// always_ff #(posedge clk, negedge arstn)
// if (!arstn)
// addr_eq_idx[i] <= 1'b0;
// else
// addr_eq_idx[i] <= (address == index[i]) ? 1'b1 : 1'b0;
end
// result has a '1' at the position where the first match is found
assign result = addr_eq_idx & ((~addr_eq_idx) + 1);
Finally, try to think if your design can be simplified due to known run-time data characteristics. For example, let's say you are 100% sure that the address you're looking for may exist within the index 2D array in at most one position. If that is the case, then you do not need an FPA at all, since the first match will be the only match. In that case, addr_eq_idx already points to the matching index, as a one-hot vector.

How to look at a certain bit in C programming?

I'm having trouble trying to find a function to look at a certain bit. If, for example, I had a binary number of 1111 1111 1111 1011, and I wanted to just look at the most significant bit ( the bit all the way to the left, in this case 1) what function could I use to just look at that bit?
The program is to test if a binary number is positive or negative. I started off by using hex number 0x0005, and then using a two's compliment function to make it negative. But now, I need a way to check if the first bit is 1 or 0 and to return a value out of that. The integer n would be equal to 1 or 0 depending on if it is negative or positive. My code is as follows:
#include <msp430.h>
signed long x=0x0005;
int y,i,n;
void main(void)
{
y=~x;
i=y+1;
}
There are two main ways I have done something like this in the past. The first is a bit mask which you would use if you always are checking the exact same bit(s). For example:
#define MASK 0x80000000
// Return value of "0" means the bit wasn't set, "1" means the bit was.
// You can check as many bits as you want with this call.
int ApplyMask(int number) {
return number & MASK;
}
Second is a bit shift, then a mask (for getting an arbitrary bit):
int CheckBit(int number, int bitIndex) {
return number & (1 << bitIndex);
}
One or the other of these should do what you are looking for. Best of luck!
bool isSetBit (signed long number, int bit)
{
assert ((bit >= 0) && (bit < (sizeof (signed long) * 8)));
return (number & (((signed long) 1) << bit)) != 0;
}
To check the sign bit:
if (isSetBit (y, sizeof (y) * 8 - 1))
...

Why does uint break my for loop?

This is not really a problem as the fix is simple and pretty costless. I'm guessing it's some property of for or uint that I don't understand and I just would like to know what is going on so...
Using ActionScript 3 I set up a for loop to run backwards through the elements of a Vector.
var limit:uint = myVector.length-1;
for(var a:uint = limit; a >= 0; a--)
{
trace(a);
}
When I run this it outputs 2, 1, 0 as expected but then moves on to 4294967295 and begins counting down from there until the loop times out and throws an Error #1502.
The fix is simply to type a as int rather than uint but I don't get why. Surely I am dealing with values of 0 and greater so uint is the correct data type right?
I guess that 4294967295 is the max value for uint but how does my count get there?
If you do
var myUint:uint = 0;
trace(myUint - 1);
Then the output is -1 so why, in my loop should I suddenly jump back up to 4294967295?
Sorry for the slightly rambling question and cheers for any help.
You are close. As you said, your loop gives you 2, 1, 0, 4294967295. This is because uint can't be negative. Your loop will always run while a >= 0 and since it is never -1 to break the loop condition, it continues to loop forever.
var myUint:uint = 0;
trace(myUint - 1);
I didn't test this but what is probably happening is that myUint is being converted to an int and then having 1 subtracted. The following code should be able to confirm this.
var myUint:uint = 0;
trace((myUint - 1) is uint);
trace((myUint - 1) is int);
To fix your loop you could use int or you could use a for each(var x:Type in myVector) loop if you don't need the index (a).
an iteration and a a-- will occur when a is 0, thus as your int is not signed, the max value for this type will be set -> this is the way minus values are set in unsigned types.
Change your code into:
var limit:uint = myVector.length-1;
for(var a:uint = limit; a > 0; a--)
{
trace(a);
}
In binary - first BIT of number is minus, that is in int values. In UINT value that is just a BIT of value.
One byte int looks like 1000 0000 == -127 and 0111 1111 = 127
One byte uint looks like 1000 0000 == 128 and 0111 1111 = 128
This is it.

Space complexity confusion

I'm a bit confused about analyzing space complexity in general. I'm not sure the meaning of "extra space taken up by the algorithm". What counts as space of 1?
In the example here
int findMin(int[] x) {
int k = 0; int n = x.length;
for (int i = 1; i < n; i++) {
if (x[i] < x[k]) {
k = i;
}
}
return k;
}
The space complexity is O(n), and I'm guessing it's due to an array size of n.
But for something like heapsort, it takes O(1). Wouldn't an in-place heapsort also need to have an array of size n(n is size of input)? Or are we assuming the input is already in an array? Why is heapsort's space complexity O(1)?
Thanks!
Heapsort requires only a constant amount of auxiliary storage, hence O(1). The space used by the input to be sorted is of course O(n).
Actually extra space corresponds to extra stack space that an algo uses i.e. other dan the input and generally it requires stack in recursive function calls , if recursion is present in algo than surely it will use stack to store contents until it get solved by termination condition.
The size of the stack will be O(height of the recursion tree).
Hope this is helpful!!

"not less than" versus "greater or equal to" speed

I was wondering if someone knew or has one of those accurate speed tests could test
"not less than" versus "greater or equal to" speed in Actionscript 3 (Air 2.5 if that makes a difference)?
I have virtual machines running on this computer and I am getting very inaccurate results.
Using it as such
if ( !(__index < _vector.length) ) return;
or
if ( __index >= _vector.length ) return;
I would have thought the first one, since all its doing is 1 test and then reversing it, but actionscript 3 has some of those quirks where you can never be sure.
There shouldn't be a difference in speed, in theory. ActionScript uses the nanojit JIT library to compile code, and I know for a fact (having worked on that code before in Mozilla's JavaScript engine, which shares nanojit with Adobe's ActionScript) that the code to implement comparisons will transform simple conversions like inversion of a comparison into the inverse comparison. So in theory the only difference is another cycle or two spent to compile the code. This is not worth worrying about.
On the other hand, modern CPUs are complex beasts, and infinitesimal perturbations can make notable differences. So while I'd lay strong odds on there being no difference between the two, I wouldn't bet the farm on it.
Your question concerns computer science more than it does action script specifically as most languages will attempt to compile to the most optimal machine code as possible.
So, I will use a C++ example to answer your question.
int j = 16;
if (!(j < 10))
{
int l = 3;
}
if (j >= 10)
{
int l = 3;
}
This produces the following key section in assembly:
00231375 cmp dword ptr [j],0Ah
00231379 jl wmain+32h (231382h)
0023137B mov dword ptr [l],3
00231382 cmp dword ptr [j],0Ah
00231386 jl wmain+3Fh (23138Fh)
00231388 mov dword ptr [l],3
0023138F xor eax,eax
Lines 00231375 and 00231382 are your actual tests contained in the if statement. As you can see, both my < and >= tests were compiled as the same identical code in assembly (when comparing two integers). Therefore, either test will take the same amount of time on the CPU since they both result in the same test (if left < right, skip if block). This will most likely be the case with the action script compiler.
However, one question could be if the JIT compiler takes longer to compile !([int] < [int]) or [int] >= [int]. My guess is that the difference is probably not enough to matter.
make a loop and use getTimer() to discover. Try something like this:
var startTime:int = getTimer()
var count:int = 1000000
for (var i:int = 0;i<count;i++) {
if ( !(__index < _vector.length) ){
}
}
trace("The first script took "+String(getTimer()-startTime) + "ms to run")
startTime = getTimer()
for (i = 0;i<count;i++) {
if ( __index <= _vector.length ){
}
}
trace("The second script took "+String(getTimer()-startTime) + "ms to run")
Also, if you get innacurate results with this tecnique, try making the count variable bigger. Removing the "_vector.lenght" verification from the loop may be usefull if you just need to check the ">" and ">=" performance