Division and Power in Javascript - javascript

I have the following code to divide a variable by 100 and power it.
var a = 1;
var b = (a / 100) ^ 2;
The value in 'b' becomes 2 when it should be 0.01 ^ 2 = 0.0001.
Why is that?

^ is not the exponent operator. It's the bitwise XOR operator. To apply a power to a number, use Math.pow():
var b = Math.pow(a / 100, 2);
As to why you get 2 as the result when you use ^, bitwise operators compare the individual bits of two numbers to produce a result. This first involves converting both operands to integers by removing the fractional part. Converting 0.01 to an integer produces 0, so you get:
00000000 XOR 00000010 (0 ^ 2)
00000010 (2)

Try this:
2 ^ 10
It gives you 8. This is easily explained: JS does not have a power operator, but a XOR: MDN.
You are looking for Math.pow (MDN)

Power in javasript is made with Math.pow(x, y) function, not typing ˆ in between.
http://www.w3schools.com/jsref/jsref_pow.asp

Update 2021:
Exponentiation operator is available since ECMAScript 2016.
So, you can do something like:
var b = (a / 100) ** 2;

Related

How can i check if two numbers start with the same digits Javascript

I need to check if two numbers start with the same digits, like startsWith but for numbers,
like,
let a = 567
let b = 5
a.startsWith(b) should return true, but it is returning not a function.
Convert a to a String as startsWith method is available on Strings.
NOTE: You can explicitly choose to convert b to a String but JavaScript will do it implicitly.
const
a = 567,
b = 5;
console.log(String(a).startsWith(b));
Convert it to string.
a.toString().startsWith(6)
Your current variable is a number and it doesn't have startsWith method. startsWith method works on string. so you would need that conversion.
You could try converting the numbers to strings first:
let a = 567;
let b = 5;
console.log(a.toString().startsWith(b.toString()))
Two alternative solutions to String and toString(), just to be thorough:
let
a = 567,
b = 5;
console.log(`${a}`.startsWith(b));
console.log(('' + a).startsWith(b));
For completeness' sake, you can use mathematics to do the comparison. But it is a bit involved.
To compare two arbitrary integers, you need to get them to a common magnitude - which power of 10 a number is in.
To get that, you need to do extract the base 10 logarithm of the number and only take the integer part: log10 567 is 2.75 of which you just need 2. While log10 5 is 0.70 of which you need 0.
When you have the exponents of each, then you can get the size to reduce the first number with the second exponent subtracted from the first exponent: 2 - 0 = 0
Drop digits off the end of the number by doing an integer division by 10 to the power of the common exponent found in 3. so Math.floor(567 / 10 ** 2) which gives us 5.
The divisor needs to further be capped to be not lower than 0. Otherwise a negative power of 10 will increase the number: 567 / 10 ** -2 is 56700 and we do not want to do that.
After the two numbers are brought to the same magnitude, compare them.
function startsWithInteger(a, b) {
//get which power of 10 each number is in
const exponentA = Math.floor(Math.log10(a));
const exponentB = Math.floor(Math.log10(b));
//get magnitude to compare the two. Cap at 1 (10 ** 0)
let comparativeMagnitude = 10 ** Math.max((exponentA - exponentB), 0);
//get the "start of" of `a` with an intiger division
//by the common power of 10 to get the same number of digits
const startA = Math.floor(a / comparativeMagnitude);
return startA === b;
}
console.log(startsWithInteger(567, 2)); //false
console.log(startsWithInteger(267, 2)); //true
console.log(startsWithInteger(567, 50)); //false
console.log(startsWithInteger(567, 56)); //true
console.log(startsWithInteger(567, 5670)); //false
console.log(startsWithInteger(567, 567)); //true
With all that said, comparing as strings is a lot more convenient as you do not have to do all these operations or handle different cases that arise from this. For example, this is guaranteed to work for integers only, passing in numbers with a decimal part can give the wrong result.

Javascript, different between b^2 and b * b

I try coding in Javascript to find the result of a second linear regression and found the result as attached:
and the result is different ???
This is because the ^ operator is not how Javascript does powers. The ^ operator is the bitwise XOR operator.
To square a value you would need to use Math.pow() or **. As in:
b * b
Math.pow(b, 2);
b ** 2
* is arithmetic multiplication operator.
^ is bitwise XOR operator.
To raise a number to a power use arithmetic exponentiation operator ** (introduced in ECMAScript 7 - see browser support) or Math.pow function.

What is the use of "|" (pipe) symbol in a JS array

I have a JS array which is being used as follows in our existing code:
temp = charArray[0 | Math.random() * 26];
Wanted to know what exactly is the usage of "|" symbol in the above code and are there more such operators?
From the MDN:
Bitwise operators treat their operands as a set of 32 bits (zeros and
ones) and return standard JavaScript numerical values.
As the 32 bit part is (a part of) the integer part of the IEEE754 representation of the number, this is just a trick to remove the non integer part of the number (be careful that it also breaks big integers not fitting in 32 bits!).
It's equivalent to
temp = charArray[Math.floor(Math.random() * 26)];
| is bitwise OR, which means, that all bits that are 1 in either of the arguments will be 1 in the result. A bitwise OR with 0 returns the given input interpreted as an integer.
In your code the its majorily used to convert the
Math.random()
number to integer. The bottom line is :
var a = 5.6 | 0 //a=5
Explanation:
Lets take
var a = 5; //binary - 101
var b = 6; //binary - 110
a|b a|a a|0
101 101 101
110 101 000
------ ------ ------
111-->7 101-->5 101-->5

Javascript Modular Arithmetic

Javascript evaluates the following code snippet to -1.
-5 % 4
I understand that the remainder theorem states a = bq + r such that 0 ≤ r < b.
Given the definition above should the answer not be 3? Why does JavaScript return -1?
Because it's a remainder operator, not a modulo. But there's a proposal for a proper one.
A quote from Ecma 5.1
remainder r from a dividend n and a divisor d is defined by the
mathematical relation r = n − (d × q)
where q is an integer that is negative only if n/d is negative and
positive only if n/d is positive
Most programming languages use a symmetric modulo which is different than the mathematical one for negative values.
The mathematical modulo can be computed using the symmetric modulo like this:
a mod b = ((a % b) + b) % b
mod mathematical modulo
% symmetric modulo
The reason is that % is not a modulus but a remainder operator. See here
If you're using % to do modular arithmetic, it doesn't matter (conceptually, at least) whether -5 % 4 evaluates to –1 or 3, because those two numbers are congruent modulo 4: for the purposes of modular arithmetic, they're the same.
...if the remainder is nonzero, there are two possible choices for the remainder, one negative and the other positive, and there are also two possible choices for the quotient. Usually, in number theory, the positive remainder is always chosen, but programming languages choose depending on the language and the signs of a and n. (http://en.wikipedia.org/wiki/Modulo_operation)
in python, which takes the sign of divisor:
-5 % 4 == 3 # -5 = (-2) * 4 + 3
in javascript, which takes the sign of divident:
-5 % 4 == -1 # -5 = (-1) * 4 - 1

JavaScript - Find out how many times a number goes into another number evenly

Is there a simple way to find how many times a number goes into another number evenly in JavaScript?
Say 11 divided by 4 --- I know 4 goes into 11 2 times evenly
I have this code but I thought there was a simpler way that I maybe forgetting?
<script>
a = 11;
b = 4;
i = a % b;
i2 = a - i;
solution = i2 / b;
document.write(solution); // 2
</script>
What about...
Math.floor(11 / 4);
If you're wanting to handle negative numbers (thanks Ted Hopp), you could use ~~, |0 or any other bitwise trick that will treat its operand as a 32 bit signed integer. Keep in mind, besides this being confusing, it won't handle a number over 32bits.
~~(11 / 4);
You can use this trick:
(a / b) >> 0
Shifting by 0 truncates the fractional part. This will always round toward 0, which Math.floor will not do with negative numbers.

Categories