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)));
Related
I'm doing this math which is (a - b) / a = number but javascript doesn't return the correct value
Here is my code
6200000 - 5800000 / 6200000
it should return 0.06451 but it returns
5799998.931034483
How can I get only 0.06 ?
Try using parenthesis to evaluate the subtraction first and toFixed():
var n = ((6200000 - 5800000) / 6200000).toFixed(2);
console.log(n);
use brackets
(6200000 - 5800000) / 6200000
division happens before subtraction .. to avoid it , use brackets
if you want two digits in decimal use
((6200000 - 5800000) / 6200000).toFixed(2)
((6200000 - 5800000) / 6200000).toFixed(2)
Order of math operations.
It'll run the divison before the subtraction.
To increase the order of the subtraction you can stick it in brackets.
(6200000 - 5800000) / 6200000
To shrink it to 2 decimal places add a toFixed function.
((6200000 - 5800000) / 6200000).toFixed(2)
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.
Let's say I have x = 12.345. In javascript, what function floatToInt(x) has the fastest running time such that floatToInt(12.345) returns 12?
Great Question! I actually had to deal with this the other day! It may seem like a goto to just write parseInt but wait! we can be fancier.
So we can use bit operators for quite a few things and this seems like a great situation! Let's say I have the number from your question, 12.345, I can use the bit operator '~' which inverts all the bits in your number and in the process converts the number to an int! Gotta love JS.
So now we have the inverted bit representation of our number then if we '~' it again we get ........drum roll......... our number without the decimals! Unfortunately, it doesn't do rounding.
var a = 12.345;
var b = ~~a; //boom!
We can use Math.round() for that. But there you go! You can try it on JSperf to see the slight speed up you get! Hope that helps!
this is a good example i think
var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue );
var intvalue = Math.round( floatvalue );
just do:
~~(x + 0.5)
Cheers, Z.
Arithmetic OR with zero does the trick.
> 12 === (0 | 12.245)
true
parseInt(x) does the work.
If you were running checks to see if the returned value is actually an int without the knowledge of what is the input.
x = 12.245; // Issa number
x = 'School'; // Not a number
y = parseInt(x)
if isNaN(y)
console.log('Not a number');
else
console.log('Issa number');
// Issa number
while using y = ~~x is a totally different case
x = 12.245; // Issa number
x = 'School'; // Issa number
y = ~~x;
if isNaN(y)
console.log('Not a number');
else
console.log('Issa number');
If you don't care about the rounding specifics, Math.trunc() is easy, standard, and readable. I haven't tested performance, but it must be better than Math.round() and parseInt().
In my own testing, I've found that the rule of thumb for performance is:
Bitwise operations (~~num, num|0, num^0, num&0xFFFFFFFF)
Math methods
num - (num % 1)
parseInt
The issue with bitwise operators is that the numbers will be cast to 32bit integers in the process, if that is fine for your use-case then go ahead. See MDN docs on bitwise OR, bitwise NOT, bitwise AND and bitwise XOR or their respective ECMAScript documentation.
The parseInt function is usually way slower than the alternatives, most likely because it expects a string as parameter.
The solution with the modulo operator should be used with caution as it may bite you in the ass sometime due to floating point issues but is almost as fast as the Math methods.
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;
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