JavaScript losowa liczba dodatnia lub ujemna
Muszę utworzyć losowy -1 lub 1, aby pomnożyć już istniejącą liczbę przez. Problem polega na tym, że moja obecna funkcja losowa generuje -1, 0 LUB 1. Jaki jest najskuteczniejszy sposób na to?
5 answers
Nie używaj istniejącej funkcji - po prostu wywołaj Math.random()
. If
var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-23 03:03:01
Zawsze byłem fanem
Math.round(Math.random()) * 2 - 1
To ma sens.
-
Math.round(Math.random())
daje 0 LUB 1 -
Mnożenie wyniku przez 2 daje 0 lub 2
A następnie odjęcie 1 daje -1 lub 1.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-06 22:05:04
Tylko dla zabawy:
var plusOrMinus = [-1,1][Math.random()*2|0];
Lub
var plusOrMinus = Math.random()*2|0 || -1;
Ale używaj tego, co myślisz, że będzie możliwe do utrzymania.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-23 09:46:56
Dlaczego nie spróbujesz:
(Math.random() - 0.5) * 2
50% szans na uzyskanie wartości ujemnej z dodatkową korzyścią wynikającą z posiadania Wygenerowanej liczby losowej.
Lub jeśli naprawdę potrzebujesz a -1/1:
Math.ceil((Math.random() - 0.5) * 2) < 1 ? -1 : 1;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-20 22:51:30
Istnieje naprawdę wiele sposobów, aby to zrobić, jak pokazują poprzednie odpowiedzi.
Najszybsza jest kombinacja matematyki.round () I Math.losowe:
// random_sign = -1 + 2 x (0 or 1);
random_sign = -1 + Math.round(Math.random()) * 2;
Możesz także używać matematyki.cos () (, które jest również szybkie):
// cos(0) = 1
// cos(PI) = -1
// random_sign = cos( PI x ( 0 or 1 ) );
random_sign = Math.cos( Math.PI * Math.round( Math.random() ) );
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-30 01:05:35