Incremental Correctness Recursive Algorithm in JavaScript - javascript

The pseudocode for incrementing natural numbers using a recursive algorithm is like this (example from the Algorithm Design Manual by Steven S. Skiena):
Increment(y)
if y = 0 then return(1) else
if (y mod 2) = 1 then
return(2 * Increment(y/2))
else return(y + 1)
I implemented it with JavaScript here: https://repl.it/#danielmai/IncrementalNaturalNumbers
function increment(y) {
if(y == 0) return 1
if(y % 2 == 1) {
return 2 * increment(y / 2)
}
else return y + 1
}
It doesn't work for odd numbers. I found out that JavaScript rounds up numbers with 0.5 or higher, so if y is odd, it will increment twice, i.e 5 -> 7.
I can use Math.floor(y/2) to make it round down, but I assume this function should work regardless of rounding up or down. So my question is, is there a way to correct this recursive function in JS without using Math.floor?

This has nothing to do with javascript rounding numbers up with 0.5 or higher.
Your increment function is asuming x / 2 will return an integer, but in javascript this will give a decimal number when odd. So when doing increment(3), you are recursively calling increment(1.5). As 1.5 % 2 = 1.5, its not == 1 so it ends up returning 2.5. So in the end, you end up returning 2.5 * 2 = 5.
This funcion would indeed work on c++ where if you are working with integers, division will trim trailing decimals. However, in javascript addition +, subtraction -, multiplication *, division /, power **, and modulo % all treat numbers in JavaScript as a double. Only binary operators treat numbers in JavaScript as a signed 32 bit integer.

Javascript doesn't have integer division, so you can't just do 5/2 and expect it to give you 2.
If you're looking for an alternative to Math.floor, this website has you covered. It has all of the alternatives you could ever want, and can check which will be the fastest on your browser.

Related

Write a function that returns the square of a number without using *,+ or pow

The task is to write a function that takes n as an input where n is a number (from -32768 to 32768) and returns the square of that number. Simple task except for the fact that we cannot use any operators such as *,+ or even use any Math. functions such as pow. eval is not allowed as well.
Even more challenging is that we must keep the character code count less than 39 characters.
I absolutely cannot think of a way to get the square of a number without using the + or *. And even worse, to keep the character count less, it's impossible for me.
Codes like this won't work because: I used the plus sign and the character count is more than 60.
function sq(n){
var res=n;
for(i=1;i<n;i++)
res+=n;
return res;
}
If n is a decimal, we are expected to return the nearest whole number as the result.
Thank you for reading all of this!
Edit: My problem has been solved. Thank you to everyone who has tried to help me with their codes as it helped me gain a new aspect of solving each problems.
Thank you very much again!
You can try this as well
function multiply(a) {
return a / (1 / a);
}
console.log(multiply(6))
console.log(multiply(4))
The repeat() method returns a new string with a specified number of copies of the string it was called on. See here
This approach is limited to positive and integer numbers only.
// Another method
function multiplytwo(a) {
return ("i").repeat(a).repeat(a).length
}
console.log(multiplytwo(4))
console.log(multiplytwo(25))
//creating a string “i” and repeating it “a” times, then repeats that “a” times, and then returning the length.
You could divide n by 1 / n
For rounding off without using Math.round, I have used this:
s=n=>(r=>(r-~~r<.5?0:1)- -~~r)(n/(1/n))
console.log(s(5));
console.log(s(4.4));
console.log(s(-4.44));
This has 39 characters.
** is not in your list, so you might be able to use it:
sq = n => n ** 2
console.log(sq(5));
You could also use - twice, instead of +:
sq=n=>{s=0;for(let i=n;i>0;i--)s=s-(-n);return s}
console.log(sq(5));
(function definition is 49 characters)
If anyone still needs a solution that passes tests.
#adiga's solution works nicely. But if you need to be under 39 characters you can exploit JS implicit type coercion: substitute r-~~r<.5?0:1 by r-~~r<.5. It will give you a boolean which will be coerced to either 1 or 0. So, final solution is following:
s=n=>(r=>(r-~~r<.5)- -~~r)(n/(1/n))
As this just got brought back up, here is a 22-character solution:
sq=n=>~~-(-.5-n/(1/n))
;[[0, 0], [1, 1], [2, 4], [3, 9], [4.4, 19], [-4.44, 20], [32768, 1073741824]]
.forEach (([n, s]) => console .log (`sq(${n}) == ${s} //=> ${sq(n) == s}`))
Explanation
Like other answers here it takes advantage of the fact that n / (1/n) is mathematically equivalent to squaring n. This is also helped by the fact that although 1 / 0 is Infinity, 0 / Infinity gives back 0. Mathematically this is iffy, but for the problem it's perfect. The trick is then to round this to the nearest integer. We could do so like this:
let sq = (n) => Math .round(n / (1 /n) + 0.5)
But we have two issues here. First we take the fact that Math.round is disallowed by the rules. Here we can use a common substitution for Math.round, namely ~~. This is simply two consecutive applications of the bitwise NOT operator, which first removes any fractional part to convert the result to a 32-bit integer, then inverts all the bits. Doing it a second time acts much like integer truncation, giving something more like:
let sq = (n) => ~~ (n / (1 /n) + 0.5)
But we still have a + in the definition, also disallowed. But that can be replaced by subtracting the negation of the value, with a version like this:
let sq = (n) => ~~ (n / (1 /n) - -0.5)
Now, minifying this would give us
sq=(n)=>~~(n/(1/n)- -.5)
and this is an equivalent 22-character solution. But for some reason I really didn't like the space in that version, and since (a - b) is equivalent to - (b - a), we can create this alternative:
let sq=n=>~~-(-.5-n/(1/n))
I'm not generally much of a code-golfer. I simply don't see the point. But this was a fun little challenge.

Math.sin() Different Precision between Node.js and C#

I have a problem in precision in the last digit after the comma.The javascript code generates one less Digit in compare with the C# code.
Here is the simple Node.js code
var seed = 45;
var x = Math.sin(seed) * 0.5;
console.log(x);//0.4254517622670592
Here is the simple C# code
public String pseudorandom()
{
int seed = 45;
double num = Math.Sin(seed) * (0.5);
return num.ToString("G15");//0.42545176226705922
}
How to achieve the same precision?
The JavaScript Number type is quite complex. It looks like floating point number will probably be like IEEE 754-2008 but some aspects are left to the implementation. See http://www.ecma-international.org/ecma-262/6.0/#sec-number-objects sec 12.7.
There is a note
The output of toFixed may be more precise than toString for some
values because toString only prints enough significant digits to
distinguish the number from adjacent number values. For example,
(1000000000000000128).toString() returns "1000000000000000100", while
(1000000000000000128).toFixed(0) returns "1000000000000000128".
Hence to get full digit accuracy you need something like
seed = 45;
x = Math.sin(seed) * 0.5;
x.toFixed(17);
// on my platform its "0.42545176226705922"
Also, note the specification for how the implementation of sin and cos allow for some variety in the actual algorithm. It's only guaranteed to within +/- 1 ULP.
Using java the printing algorithm is different. Even forcing 17 digits gives the result as 0.42545176226705920.
You can check you are getting the same bit patterns using x.toString(2) and Double.doubleToLongBits(x) in Java.
return num.ToString("G15");//0.42545176226705922
actually returns "0.425451762267059" (no significant digit + 15 decimal places in this example), and not the precision shown in the comment after.
So you would use:
return num.ToString("G16");
to get "0.4254517622670592"
(for your example - where the significant digit is always 0) G16 will be 16 decimal places.

Why plus sign in front of JavaScript equation with toFixed?

I was just going through the source code of particles.js and came across the following line of code:
this.speed.x = +((-options.maxSpeedX / 2) +
(Math.random() * options.maxSpeedX)).toFixed(2);
That line of code can be found HERE too.
Now the + sign right at the beginning of the expression has no difference in the equation. E.g.
(-2 + 5) = 3
Now...
+(-2 + 5) = 3
Another example:
(-5 + 2) = -3
Now..
+(-5 + 2) = -3
Why the plus sign at the beginning of the expression when it makes no difference to the outcome of the equation?
Your code is basically
x = +someNumber.toFixed(2);
Which is
x = +(someNumber.toFixed(2));
because the function call has a higher precedence than the + operator.
This makes
x = +(someNumberFormattedAsARoundedString);
Applying the unary plus operator converts the string back to a number. The net result is the rounding of the initial someNumber.
In this specific case you linked to, this looks like bad practice due to ignorance of what is a IEEE754 floating point number. It looks like the author tried to get fixed precision numbers, thus confusing the number storage and their representation (i.e. formatting).
.toFixed() returns a String. You need to cast it to Number. The unary plus + operator is used to convert/cast the string to number.
Returns
A string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If numObj is greater than 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation.
It is not required in the cases when the result is already a number. Example, +(-2 + 5).
However, in below operation it is required.
this.speed.x = +((-options.maxSpeedX / 2) +
(Math.random() * options.maxSpeedX)).toFixed(2);

Math.random and arithmetic shift

If I have the following code in JavaScript:
var index1 = (Math.random() * 6) >> 0;
var index2 = Math.floor(Math.random() * 6);
The results for index1 or index2 are anywhere between 0 and 6.
I must be confused with my understanding of the >> operator. I thought that by using arithmetic shift that the results for index1 would be anywhere between 1 and 6.
I am noticing, however that I don't need to use Math.floor() or Math.round() for index1 if I use the >> operator.
I know I can achieve this by adding 1 to both indexes, but I was hoping there was a better way of ensuring results are from 1 to 6 instead of adding 1.
I'm aware that bitwise operators treat their operands as a sequence of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.
UPDATE:
I saw the original usage in this CAAT tutorial on line 26 and was wondering whether that would actually return a random number between 1 and 6 and it seems it would only ever return a random number between 0 and 6. So you would never actually see the anim1.png fish image!
Thank you in advance for any enlightenment.
Wikipedia says '(Arithmetic right shifts for negative numbers would be equivalent to division using rounding towards 0 in one's complement representation of signed numbers as was used by some historic computers.)'
Not exactly an answer, but the idea is that >> 0 is really specific and shouldn't be used in general for getting a range between 1 and 6.
Most people would tell you to do
Math.floor((Math.random()*10)+1);

Negative Number to Non-Integer Power in Javascript

I'm writing a script that has to do something like this at one point: Math.pow(-2,1.5). The result should be approximately -2.82843, but instead, Javascript returns NaN. (I tried this in both Google Chrome 17 and Mozilla Firefox 11.) If the exponent is an integer, such as in Math.pow(-2,3), then Javascript will return the right answer, which, in this case, is -8. Positive numbers also correctly raise to non-integer powers; Math.pow(2,1.5) evaluates to approximately 2.8284271247461903. Is there any way that I can get Javascript to calculate the value of a negative number to a non-integer power?
Math.pow(-2, 1.5) returns NaN because there is no real number which equals -2 taken to the power 1.5. There is a complex number with this property, but Math.pow() doesn't do calculations using complex numbers.
This simple transformation demonstrates that this is the case:
(-2)1.5 = (-2)1 * (-2)0.5 = (-2) * sqrt(-2) = (-2) * i * sqrt(2) = -2i * sqrt(2)

Categories