I need to create a random -1 or 1 to multiply an already existing number by. Issue is my current random function generates a -1, 0, or 1. What is the most efficient way of doing this?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Don't use your existing function - just call
Math.random()
. If < 0.5 then -1, else 1:I'm using underscore.js shuffle
I've always been a fan of
as it just sort of makes sense.
Math.round(Math.random())
will give you 0 or 1Multiplying the result by 2 will give you 0 or 2
And then subtracting 1 gives you -1 or 1.
Intuitive!
why dont you try:
50% chance of having a negative value with the added benefit of still having a random number generated.
Or if really need a -1/1:
There are really lots of ways to do it as previous answers show.
The fastest being combination of Math.round() and Math.random:
You can also use Math.cos() (which is also fast):
Just for the fun of it:
or
But use what you think will be maintainable.