Bitwise NOT in ruby - javascript

I have a formula in JS that uses the bitwise NOT operator.
~~(n/m + 0.5) * m;
How do I write the same expression in ruby? There is no bitwise NOT operator in ruby.

won't this help? http://www.techotopia.com/index.php/Ruby_Operators#Ruby_Bitwise_Operators
~ Bitwise NOT (Complement)

I believe the same expression in Ruby would be (n/m + 0.5).to_i * m, or, alternatively, Integer(n/m + 0.5) * m.
It looks like the doubled bitwise complement there is really being used to truncate the decimal part of the calculation, in order to compute the nearest n such that n is a multiple of m. (In another language, I would say "convert to integer", but Javascript has a unified arithmetic type.)
Update: Mladen Jablanović suggests a cast, and yes, if both m and n are Fixnum, it's needed. In Ruby 1 / 3 is 0 but in JS it's 0.333... Here is a refined suggestion:
(n.to_f / m).round * m

Related

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.

Result of -1%7 is different in javascript(-1) and python(6)

The expression -1 % 7 in JavaScript is giving me -1 as the result. Whereas in Python and Haskell, I found the result to be 6.
Can anyone explain why both have different behaviors? Which one is correct?
I'm going to give a slightly different answer. As others have said, functions can do whatever you define them to and m - x = -x mod m. As a prelude, I'll note that Haskell has two "mod" functions, mod and rem which differ in just this aspect. You can make a case that the mod one is preferable mathematically. The rem one corresponds to what you'd get on an x86 processor. There is, in fact, a third one, the Euclidean one, which may be even better as well as described by Raymond Boute in The Euclidean Definitions of the Functions Div and Mod. The third form always returns a positive modulus. (There are, in fact, at least two other choices that can be made.)
So, Javascript's definition is what you get from most machine mod opcodes. In this sense, it might be preferable as this would make it more efficient to implement. Mathematically, Haskell's and Python's definition is better than Javascript's. There's also a third definition which may be slightly better.
One key property that the Euclidean and Haskell/Python definitions both possess is x mod m = y mod m is equivalent to x = y mod m which Javascript's definition lacks. You can verify by calculating 6 % 7 in Javascript.
Both are correct. Some languages return positive modulo numbers, while others retain their sign.
You can simply add the modulus to your variable to get a positive number, or check if the number is positive or negative before performing the modulus operation and correct the result after to switch between the two.
Pseudocode to convert a%b between the two:
In a language where -1%7 == -1, you do this to get a positive number:
((a%b)+b) % b
And in a language where -1%7 == 6 you can do this to get the signed version:
if a < 0:
return (a%b)-b
else:
return a%b
Both are correct, they just use different conventions regarding the handling of negative operands. For positive numbers, the conventions coincide, but for negative numbers they do not. In Python a % b always has the same sign as b.
In what follows, I'll use Python notation, where // is used for integer division.
Let
q, r = a // b, a % b
Then
a == q * b + r
must be true in any language (assuming a and b are integers, with b not equal to zero). So the way the remainder is handled has to be consistent with the convention used for integer division. In Python, integer division is floor division, i.e., the result is rounded towards negative infinity. In some other languages rounding towards zero is used instead. And in some languages, you get whatever convention the CPU manufacturer decided to implement, so the same code run on different hardware can give different results. As you can imagine, that can be somewhat annoying. :)
The % stands for different operators in JavaScript and in Python.
In JavaScript, the % stands for the Remainder operator. The documentation already points out the difference between the remainder and the modulo operation:
The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend, not the divisor. It uses a built-in modulo function to produce the result, which is the integer remainder of dividing var1 by var2 — for example — var1 modulo var2. There is a proposal to get an actual modulo operator in a future version of ECMAScript, the difference being that the modulo operator result would take the sign of the divisor, not the dividend.
(Emphasis by me)
In contrast to that: In Python, the % stands for the modulo operator. The documentation also makes a statement about the sign:
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. [...] The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
(Emphasis by me)
Both are correct.
To complete the other answers, you can also consider the divmod function in Python:
Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).
>>> divmod(-1, 7)
(-1, 6)

Division and Power in 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;

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

How to write Mathematical formula with "^" (caret) in JavaScript?

I need some help how to make this math formula in javascript. i have tried searching but couldn't really find cause i dont even know what ^ is called in English.
Thanks in advance
Math.floor(20*(1.1^(x-10)));
Math.floor(20*(Math.pow(1.1, (x-10))));
^ is the bitwise XOR operator - not what you want. Use the Math.pow function for exponentiation:
Math.floor( 20 * (Math.pow(1.1, x - 10)) );
Set this up in a function so you can use x for whatever value it may be:
var eq = function(x) {
return Math.floor( 20 * (Math.pow(1.1, x - 10)) );
};
Math.pow() is what you are looking for.
^, as used in other languages, is called the power or exponential operator, but in Javascript, it serves a different purpose, it is the bitwise XOR operator.
Math.floor(20*(Math.pow(1.1, x - 10)));

Categories