JavaScript Random Positive or Negative Number

后端 未结 6 1849
孤独总比滥情好
孤独总比滥情好 2021-01-30 06:32

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

6条回答
  •  生来不讨喜
    2021-01-30 07:18

    There are really lots of ways to do it as previous answers show.

    The fastest being combination of Math.round() and Math.random:

    // random_sign = -1 + 2 x (0 or 1); 
    random_sign = -1 + Math.round(Math.random()) * 2;   
    

    You can also use Math.cos() (which is also fast):

    // cos(0) = 1
    // cos(PI) = -1
    // random_sign = cos( PI x ( 0 or 1 ) );
    random_sign = Math.cos( Math.PI * Math.round( Math.random() ) );
    

提交回复
热议问题