I was trying to implement the Javascript-method Math.clz32 in Python. The method I've been able to come up with is:
def clz32(x):
x = x % 2 ** 32
if x == 0: return 32
return 34 - len(bin(x))
This method works, but I've been wondering whether there is a pure mathematical formula for this.
You can use the bit_length method, which returns the number of bits required to represent the integer. Since we are only interested in the leading zero bits, we will subtract this number from 32. Note that this does not account for negative numbers, so clz32(-1) will return 0.
def clz32(x):
if x < 0:
return 0
return 32 - x.bit_length()
Related
Is there a reason why some Javascript programmers use the following syntax to remove decimals?
Math.ceil(averageCost / 10) * 10;
Why wouldn't we just use Math.ceil? Doesn't it effectively do the same thing as the above? Is there a condition where Math.ceil doesn't work?
Initially I thought maybe this would eliminate string cases and return a zero, but in the following code, the results are NaN -
var name = "Gary";
console.log(Math.ceil(name / 10)); // NaN
console.log(Math.ceil(name)); // NaN
So I'm at a loss for why I'd see a division by 10 with a subsequent multiplication of 10.
The construct:
Math.ceil(averageCost / 10) * 10;
Does a form of rounding. It has the net effect of rounding up to the nearest whole number multiple of 10. So:
11 => 20
20 => 20
21 => 30
11.99 => 20
Math.ceil(averageCost / 10) divides by 10 and rounds up to the nearest whole number (removing all decimal portions and all ones) and then the * 10 brings it back to the same numeric range it was originally in, but without the parts removed by the rounding.
Here's an example showing a number of results:
const nums = [10,11,15,18,19,20,21,10.1,11.99,20.19];
for (let num of nums) {
let result = Math.ceil(num/10) * 10;
console.log("Input: ", num, ", Output: ", result);
}
Why wouldn't we just use Math.ceil? Doesn't it effectively do the same thing as the above? Is there a condition where Math.ceil doesn't work?
This combination rounds up to the nearest whole number multiple of 10 whereas Math.ceil() only rounds up to the nearest whole number. So, the two cases you ask about have different uses. Use the one that accomplishes what you want to accomplish. For a number where the integer portion is already a power of ten such as 10.3, the two would have the same output, but for any other number such as 11.3, the two would not have the same output.
Math.ceil(11.3) === 11
(Math.ceil(11.3 / 10) * 10) === 20
Is there a condition where the Math.ceil() function in Javascript doesn't remove decimals from the output?
No. There is not. It's whole function is to round up to the nearest whole number (thus removing any decimal fraction from the number).
So I'm at a loss for why I'd see a division by 10 with a subsequent multiplication of 10.
To round up to the nearest whole number multiple of 10.
In JavaScript code where the 8 bits of a byte represent 8 Boolean "decisions" (aka: flags), there is a need to isolate each given bit for conversion to a Boolean variable. Consider my solution using String parsing:
var bitParser = function (_nTestByte, _nBitOrdinal) {
var bits = ("00000000" + _nTestByte.toString(2)).slice(-8); // convert to binary and zero-pad
return bits[_nBitOrdinal] === "1";
};
console.log(bitParser(0b10100101, 2)); // ECMAScript 6+ prefix, returns true
It works, and shows the desired result. However I have a hypothesis stating that a bit shifting technique would be a faster option than String manipulation. I tend to believe that but desire to prove it.
The problem is, I have yet to produce such a function that works correctly, let alone something I can test. I have created the following logic plan that I believe is accurate:
/*
LOGIC PLAN
----------
0) Remember: all bitwise operators return 32 bits even though we are using 8
1) Left shift until the desired bit is the left-most (highest) position;
2) Right shift (zero filling) 31 bits to eliminate all right bits
*/
The implementation of the login plan follows. Because of the 32 bit nature of bitwise operators, its my belief that the entire left 3 bytes (24 bits) must be shifted off first before we even reach the byte being worked on. Then, assuming a scenario where the 3rd bit from the left (String ordinal 2) is the desired bit, I am shifting off 2 more bits (ordinals 0 & 1), for a total of 26 bits of left shifting.
This should produce a binary number with the desired bit all the way left followed by 31 undesired zero bytes. Right shifting those 31 bits away produces a binary with 31 (now) leading zero bits which evaluates to whatever the value of the desired bit is. But of course, I would not be writing this question if THAT were true, now would I? :-)
// hardcoded, assuming the second "1" (ordinal 2) is the bit to be examined
console.log((0b10100101 << 26) >> 31); // instead of 1, returns -1
I feel like I am really close, but missing something or pushing JavaScript too hard (lol).
In JavaScript code where the 8 bits of a byte represent 8 Boolean "decisions" (aka: flags), there is a need to isolate each given bit for conversion to a Boolean variable...
If that's the actual goal, bitshifting is neither necessary nor useful: Just use a bitwise & with the desired bit, which will give you either 0 or a number with that bit set. 0 is falsy, the number with a bit set is truthy. You can either use that as-is, or force it to boolean via !!flag or Boolean(flag):
Here's your bitParser function using bitmasking:
var bitParser = function (_nTestByte, _nBitOrdinal) {
return !!(_nTestByte & Math.pow(2, _nBitOrdinal));
};
console.log(bitParser(0b10100101, 2)); // true
console.log(bitParser(0b10100101, 1)); // false
Rather than doing the Math.pow every time, of course, we'd probably be better off with a lookup table:
var bits = [
0b00000001,
0b00000010,
0b00000100,
0b00001000,
0b00010000,
0b00100000,
0b01000000,
0b10000000
];
var bitParser = function (_nTestByte, _nBitOrdinal) {
return !!(_nTestByte & bits[_nBitOrdinal]);
};
console.log(bitParser(0b10100101, 2)); // true
console.log(bitParser(0b10100101, 1)); // false
From your question I took
console.log((0b10100101 << 26) >> 31); //instead of 1, returns -1.
And to answer your question why it returned -1 instead of 1
You need to do unsigned right shift >>> instead of signed one >>
console.log((0b10100101 << 26 ) >>>31);
Yes it can, and what you're doing is almost correct.
Integers are represented as a 32bit binary number, with the leftmost bit representing the sign (it's 1 if the number is negative and 0 if the number is positive). Lets look at some of the numbers' representations:
//last 31 digits keeps increasing as the number decreases
// ...
-2 => 0b11111111111111111111111111111110
-1 => 0b11111111111111111111111111111111
0 => 0b00000000000000000000000000000000
1 => 0b00000000000000000000000000000001
2 => 0b00000000000000000000000000000010
// ...
// last 31 digits keep increasing as the number increases
Now, what you're having (0b10100101 << 26) should give you 10010100000000000000000000000000, which you'd expect to be a big negative number (because the left-most bit is 1). Then right afterwards, you have >> 31 which you're expecting to strip off all 31 bits and leave you with the left-most bit.
That should work, but it's not what's happening. And why is that? It's because the people who came up with ECMAScript thought it would make more sense if 4 >> 1 returns 2 and -4 >> 1 returns -2.
4 >> 1 // returns 2 which is 0b00000000000000000000000000000010
0b0000000000000000000000000000000100 >> 1 // returns 2, same
-4 >> 1 // returns -2, which is 0b11111111111111111111111111111110
But -4 is 0b11111111111111111111111111111100, and for your purposes right shifting it by 1 should yield 0b01111111111111111111111111111110 (big positive number, since left-post bit is 0), and that's not -2!
To overcome that, you can use the other right shift operator which doesn't care about about the sign: >>>. -4 >>> 1 is 2147483646 which is what we want.
So console.log((0b10100101 << 26) >>> 31); gives you 1, which is what you want. You can also keep using >> and regarding any negative outcome to be a result of 1 being the chosen bit.
The most simple way to achieve your actual need is to use simple conditions rather than trying to isolate bits.
var bitParser = function (_nTestByte, _nBitOrdinal) {
return (_nTestByte & _nBitOrdinal);
};
console.log(bitParser(6, 2) ? true : false); // true
console.log(bitParser(6, 1) ? true : false); // false
I adapted the console.log() expression in a way that may seem complicated.
It's only to really show the logical result at this step, while I didn't choose to use !! inside of the function, so returning a truly/falsy value rather than true|false.
Actually this way keeps all the most simple possible, because the expected use else where in the code is if (bitParser(...)), which automatically casts the result to boolean.
BTW, this works whatever is the _nTestByte size (may be more than 1 byte).
I need to calculate the modulo of a 24 digit long integer (IBAN checksum) but JS calculates wrong.
e.g.:
700901001234567890131400 % 97 = 90
but in JS (V8) it's 38.
How can I calculate the modulo in JS
I think the document you're linking to already says what you should do:
If the application software in use does not provide the ability to handle integers of this size, the modulo operation can be performed in a piece-wise manner.
Piece-wise calculation D mod 97 can be done in many ways. One such way is as follows:
Starting from the leftmost digit of D, construct a number using the first 9 digits and call it N.[Note 3]
Calculate N mod 97.
Construct a new 9-digit N by concatenating above result (step 2) with the next 7 digits of D. If there are fewer than 7 digits remaining in D but at least one, then construct a new N, which will have less than 9 digits, from the above result (step 2) followed by the remaining digits of D
Repeat steps 2–3 until all the digits of D have been processed
The result of the final calculation in step 2 will be D mod 97 = N mod 97.
It might be harder than one can think.
It's quite tricky to ensure javascript handle number as integer (it often store them as float, but not always).
Others already made libraries to handle IBAN check in JS.
Take a look at https://github.com/arhs/iban.js for instance.
The largest number that can be represented in javascript is 2^53 - 1. They are 64-bit floating point values. So the largest number is 9007199254740991.
A number greater than 9007199254740991 can not be caclcuted in normal way. So, to find the modulo of such large number you have to break it into pieces.
eg. 700901001234567890131400 can be broken into 700901001234567 and 890131400.
First find the modulo of 700901001234567.
700901001234567 % 97 = 13
Now join 13 infront of second number 13890131400 and find the modulo of this number
13890131400 % 97 = 90
I came across this problem recently and this looks like what is solvable with Horner's method [https://en.wikipedia.org/wiki/Horner%27s_method]
/**
* str is numeric.
* MOD=97 is our use case
* #return: an integer 0<=x<=97
**/
int getMod(String str, int MOD) {
int remainder = 0;
for(Character c : str.toCharArray()) {
int value = Character.getNumericValue(c);
remainder = 10*remainder + value;
remainder %= MOD;
}
return remainder;
}
Unless I don't fully understand the problem, the code above should work.
I'd like to know if there's a calculation that allows me to get the number of bits that I need to store any negative (signed) value (such as -1, -255, -1324, etc.)?
At the moment I have implemented a function to calculate this for values greater and equal to 0:
calculateBitsNeeded = function (value) {
if (value == 0) {
return 1;
}
else if (value > 0) {
return Math.floor(Math.log(value) / Math.LN2) + 1;
}
else {
//TODO ...
}
};
E.g.: If I have the number -38 I would need 7bits for storing (101 1010).
Thanks for any help :)
Assuming that you are talking about integer numbers.
To answer your question, you have to understand that on all modern platforms, integers are either considered signed, or unsigned.
JavaScript doesn't actually supports integers, they are stored as floating point values. However, a 64 bit floating point number can handle 53-bit integers with full accuracy, so it can easily handle the 16 bit integers that C uses.
I'm going to ignore those and limit my answer to 16 bit ints that you'd use to talk to C.
A 16 bit Unsigned bit integer can have the values of: 0 - 65535
A signed integer can have the values of: −32,768 to 32,767
Under both encoding, the numbers 0 - 32,767 are stored the same way. No difference in handling.
However, the numbers 32,768 - 0 are stored using a system called two's compliment.
Bit wise, the numbers -1 and 32,768 are the same. -2 and 32,767 are the same.
So, the easiest way to calculate the bits needed for a negative integer is to convert it to its signed equivalent.
To find the next odd number for an input the following code is being used:
a=5.4; // Input
b=Math.ceil(a); // Required to turn input to whole number
b=b+(((b % 2)-1)*-1); // Gives 7
The ceil rounding function is required.
Is this safe and is there a more compact way to do this?
EDIT: When the input is already an odd whole number then nothing happens. For example 5.0 will return 5
How about just
b += b % 2 ^ 1;
The remainder after dividing by 2 will always be 0 or 1, so the ^ operator (exclusive-OR) flips it to the opposite.
(Also, (b & 1) ^ 1 would work too. Oh, I guess b = b ^ 1 would work for positive integers, but it'd be problematic for big integers.)
At the question author's request:
The most compact way to achieve it is
b = Math.ceil(a) | 1;
First use ceil() to obtain the smallest integer not smaller than a, then obtain the smallest odd integer not smaller than ceil(a) by doing a bitwise or with 1 to ensure the last bit is set without changing anything else.
To obtain the smallest odd integer strictly larger than a, use
b = Math.floor(a+1) | 1;
Caveats:
Bit-operators operate on signed 32-bit integers in Javascript, so the value of a must be smaller than or equal to 2^31-1, resp. strictly smaller for the second. Also, a must be larger than -2^31-1.
If the representation of signed integers is not two's complement, but ones' complement or sign-and-magnitude (I don't know whether Javascript allows that, Java doesn't, but it's a possibility in C), the value of a must be larger than -1 -- the result of Math.ceil(a) resp. Math.floor(a+1) must be nonnegative.
Not really shorter, but this is more legible:
a=5.4;
b=Math.ceil(a);
b = b % 2 ? b : b + 1;
Try this:
a = 5.4
b = Math.ceil(a)
b = b%2 == 0 ? b+1 : b
y = Math.ceil((x - 1)/2)*2 + 1
Execute fn on http://www.intmath.com/functions-and-graphs/graphs-using-jsxgraph.php
Without Math.ceil() it can be done so:
b = a + a % 2 | 0 + 1;
NB. I consider next odd number of 5.0 as 7.