This question already has answers here:
Javascript Random Number?
(3 answers)
Closed 3 years ago.
i am using this function to generate random number between 1000 and 100.
but here according to me, in (max - min) + min, max- min =900 and min= 100, so it should not generate numbers between 900 and 100? but it is returning numbers greater than 900 also how? I am confused. and do tell how to check the range for the numbers random function is generating? any help with this?
x = Math.floor(Math.random() * (1000 - 100) + 100);
console.log(x);
The formula for random numbers Math.random() * (max - min) + min is the correct one to get a uniformly distributed number between min and max.
max - min will give you the range in which you want to generate the random numbers. So in this case 1000 - 100 results in a range of 900.
Multiplying by Math.random() will give you a random number in the range. So, with a Math.random() producing 0.5 after multiplying you get 450.
Finally, adding min back to the random pick ensures the number you get is within bounds of min and max.
For example Math.random() produces 0.01 if we substitute in the formula we get 0.01 * (1000 - 100) = 9 which is below min. Conversely, if Math.random() produces 1 then 1 * (1000 - 100) = 900 which is the highest random number possible to get from the range and yet it's still below max. In both cases adding min to the result ensures the random number you get is within max and min
The function Math.random() returns a number between 0 and 1.
When use "Math.random() * (1000 - 100)", this part of the code generates a number between 0 and 1 then multiplies it by 900, which will give you a number between 0 and 900.
Now in the last block you do add 100 to the previously generated number which results in a number between 0 and 900 + 100, which gives a result between 100 and 1000.
function random(min, max) {
console.log("Multiplying by: " + (max - min));
console.log("And adding : " + min);
return Math.floor(Math.random() * (max - min) + min);
}
console.log(random(100, 1000));
Multiply by (1000 -200) instead as you already have +100
Because in case random number generated is anything greater than 800 you end exceeding range as you're adding 100 in it everytime
x = Math.floor(Math.random() * (1000 - 200) + 100);
console.log(x);
Thumb rule :-
Math.floor(Math.random() * - ( max - ( 2 * min ) ) + min )
As Math.random() generate floats, this need to be converted to an integer.
We can use parseInt(), but there is a shorthand, the ~~ bitwise operator. Performances are known to be excellent.
console.log(
100 + ~~(Math.random() * 800)
)
One possible alternative is the web crypto api, it might be a bit slower, but with the best randomness doable. This return an integer between 0 and 256.
console.log(
100 + ~~(crypto.getRandomValues(new Uint8Array(1))[0] * 3.13)
)
This question already has answers here:
Explain Math.floor(Math.random())
(6 answers)
Closed 7 years ago.
Is this the most efficient way of randomly generating 0 or 1 in javascript?
Math.floor(Math.random() * 2);
No, Math.random() * 2 | 0 and Math.random() * 2 << 0 seem to be (marginally) faster in most browsers, which makes sense since it has one less function invocation from the Math library.
Faster alternatives:
(Math.random() * 2) | 0
~~ (Math.random() * 2)
(Math.random() * 2) << 0
I'm sorry I know this is probably not a smart question but it's driving me crazy. Given this recursive function, why is 1 not returned all the time? I mean, eventually the exponent will get to 0!
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
Thanks so much for any help.
The best way to understand is to walk through the code. Let's say you do power(2,3).
What does that do?
2 * power(2,2)
//Which expands to
2 * 2 * power(2,1)
//Which expands to
2 * 2 * 2 * power(2,0)
//Which expands to
2 * 2 * 2 * 1
When 1 is returned, it is not returned to the original function call, but just the most recent function call. Every time the power function calls itself, it puts a new invocation of itself on the stack. So for instance if we call power(2, 1), that will call power(2, 0). power(2, 0) will return its value of 1 to where it was called in power(2, 1). Then power(2, 1) will return base * power(base, exponent - 1); which is base * 1 which is 2.
This may best be understood by contrasting your recursive power function with a very similar function that does always return the value 1.
function one(base, exponent) {
if (exponent == 0)
return 1;
else
return one(base, exponent - 1);
}
Notice that the only difference between your power function and one is that the the recursive call to one is the value being returned in the recursive case.
In your power function, the value being returned is base multiplied with the value of the recursive call. Thus each recursive call to power contributes to the value ultimately being returned by the initial call; whereas, only the final call to one (when exponent is 0) contributes to the returned value.
Let's assume we call power(2, 5) [i.e. with base=2 and exponent=5].
It will evaluate in the following way:
power(2, 5) = ...
Hmmm... Let's calculate power(2, 5). Is exponent==0? No it isn't (it's 5). Then we return base*power(base, exponent-1), which actually means 2*power(2,4).
power(2, 5) = 2 * power(2, 4)
= 2 * ?
Hmmm... Let's calculate power(2, 4). Is exponent==0? No it isn't (it's 4). Then we return base*power(base, exponent-1), which actually means 2*power(2,3).
power(2, 5) = 2 * power(2, 4)
= 2 * (2 * power(2, 3))
= 2 * (2 * ?)
Hmmm... Let's calculate power(2, 3). Is exponent==0? No it isn't (it's 3). Then we return base*power(base, exponent-1), which actually means 2*power(2,2).
power(2, 5) = 2 * power(2, 4)
= 2 * (2 * power(2, 3))
= 2 * (2 * (2 * power(2, 2)))
= 2 * (2 * (2 * ?))
Hmmm... Let's calculate power(2, 2). Is exponent==0? No it isn't (it's 2). Then we return base*power(base, exponent-1), which actually means 2*power(2,1).
power(2, 5) = 2 * power(2, 4)
= 2 * (2 * power(2, 3))
= 2 * (2 * (2 * power(2, 2)))
= 2 * (2 * (2 * (2 * power(2, 1))))
= 2 * (2 * (2 * (2 * ?)))
Hmmm... Let's calculate power(2, 1). Is exponent==0? No it isn't (it's 1). Then we return base*power(base, exponent-1), which actually means 2*power(2,0).
power(2, 5) = 2 * power(2, 4)
= 2 * (2 * power(2, 3))
= 2 * (2 * (2 * power(2, 2)))
= 2 * (2 * (2 * (2 * power(2, 1))))
= 2 * (2 * (2 * (2 * (2 * power(2, 0)))))
= 2 * (2 * (2 * (2 * (2 * ?))))
Hmmm... Let's calculate power(2, 0). Is exponent==0? Yes, it is! Then we return 1.
power(2, 5) = 2 * power(2, 4)
= 2 * (2 * power(2, 3))
= 2 * (2 * (2 * power(2, 2)))
= 2 * (2 * (2 * (2 * power(2, 1))))
= 2 * (2 * (2 * (2 * (2 * power(2, 0)))))
= 2 * (2 * (2 * (2 * (2 * 1))))
= 2 * (2 * (2 * (2 * 2)))
= 2 * (2 * (2 * 4))
= 2 * (2 * 8)
= 2 * 16
= 32
Post Scriptum: You should understand that return <something> specifies result value of the innermost (i.e. the latest) function call (not the outermost, i.e. the oldest).
Because it is the result of multiplying the base by itself a certain number of times, which is how exponents work. Because base is being multiplied by power(base, exponent - 1) (and power(base, exponent - 1) itself is not being returned), each iteration where exponent is not 0 essentially adds another multiplication of the base onto the result.
As an aside, this is not a very good power function.
This question already has answers here:
Round a number to nearest .25 in JavaScript
(8 answers)
Closed 9 years ago.
Hi there I want to round down an amount to full hundred:
Examples
23009 rounded 23000,
23099 rounded 23000,
23199 rounded 23100,
My function do not work, because it rounds mathematically.
$("#span_berechnungsgrundlage").text(berechnungsgrundlage);
var berechungsgrundlage_gerundet = Math.round(berechnungsgrundlage / 100) * 100;
alert(berechungsgrundlage_gerundet);
Thank you for your help
Use Math.floor.
Math.floor - Round a number downward to its nearest integer:
var berechungsgrundlage_gerundet = Math.floor(berechnungsgrundlage / 100) * 100;
You can use Math.floor:
Math.floor(number / 100) * 100;
Demo
Just replace Math.round with Math.floor.
I have this code in JavaScript:
SolarPanels = parseInt(lRemainingWidth / (panel_width + ( 2 * lPanelInterSpace)));
and then I alert the SolarPanels value which gives NaN as output,
alert("SolarPanels "+SolarPanels);
This 1 line is a tiny part of a huge calculation, but my code seems to fail here,
with the use of alerts i've read out the values of SolarPanels, lRemainingWidth, panel_width and lPanelInterSpace
which are the following:
lRemainingwidth = 17.4.320227272727276
SolarPanels = 0
panel_width = 1.65
lPanelInterSpace = 0.02
I think it has to do with the 2 dots in lRemainingWidth, either way, I don't know how to fix it. Why the lRemainingWidth has 2 dots?
Update :
This is the part that calculates the lRemainingWidth :
if(HalforDouble === "Yes")
{
lRemainingWidth = (roof_ridge /2) + ((lRemainingHeight / Math.tan((lRoofEdgeDegrees * Math.PI) / 180)) - lRoofEdge);
}
else
{
lRemainingWidth = roof_ridge + (2 * ((lRemainingHeight / Math.tan((lRoofEdgeDegrees * Math.PI) / 180)) - lRoofEdge));
}
The values here are:
lRemainingWidth = 0
roof_ridge = 17
lRemainingHeight = 20.769000000000002
lRoofEdgeDegrees = 83.5169263071276
lRoofEdge = 0.2
Your problem is that you mix strings and numbers
Start with this code before any computation :
var roof_ridge = parseFloat(roof_ridge);
There might be other strings hidden in your code but we don't see them. Apply the same conversion on them.
lRemainingWidth = roof_ridge + (2 * ((lRemainingHeight / Math.tan((lRoofEdgeDegrees * Math.PI) / 180)) - lRoofEdge));
If roof_ridge is a string then the + does string concatenation instead of addition.
Change this to
lRemainingWidth = +roof_ridge + (2 * ((lRemainingHeight / Math.tan((lRoofEdgeDegrees * Math.PI) / 180)) - lRoofEdge));
The prefix + operator in +roof_ridge coerces its argument to a number.
It seems like a cornerstone of the issue in roof_ridge variable. This variable is instance of String class, not a number. So, when you code go to this line:
lRemainingWidth = roof_ridge + (2 * ((lRemainingHeight / Math.tan((lRoofEdgeDegrees * Math.PI) / 180)) - lRoofEdge));
the next calculation is done:
'17' + whatever_float_value = got string concatenation instead of number's sum.
To fix this just add:
lRemainingWidth = parseFloat(roof_ridge) + (2 * ((lRemainingHeight / Math.tan((lRoofEdgeDegrees * Math.PI) / 180)) - lRoofEdge));