Javascript 获取随机数,重点关注限制(抛物线曲线)
我的数学知识可能仅限于自己解决这个问题。然而,我发现了一个类似的例子,重点是中心而不是边界 我想创建带有max和min的随机数,但重点是max和min,因此接近max和min的数字应该比介于两者之间的数字出现得更频繁 我记得数学中有一个函数可以创建抛物线曲线: 使用这个,我生成了我想要的函数,应该是 y=0.05*x^2 这是我的基本想法,试图将其转换为javascript,我最终得出以下结论:Javascript 获取随机数,重点关注限制(抛物线曲线),javascript,math,random,max,min,Javascript,Math,Random,Max,Min,我的数学知识可能仅限于自己解决这个问题。然而,我发现了一个类似的例子,重点是中心而不是边界 我想创建带有max和min的随机数,但重点是max和min,因此接近max和min的数字应该比介于两者之间的数字出现得更频繁 我记得数学中有一个函数可以创建抛物线曲线: 使用这个,我生成了我想要的函数,应该是 y=0.05*x^2 这是我的基本想法,试图将其转换为javascript,我最终得出以下结论: for (let i = 0; i < 100; i++) { // Create ra
for (let i = 0; i < 100; i++) {
// Create random x with ^ 2 with max=100 and min=0
let x = Math.pow(Math.floor(Math.random() * (100 - 0 + 1)) + 0, 2);
// log the random number in the console
console.log(0.05 * x);
}
任何有想法的人?要生成具有所需分布的随机数,可以使用斯米尔诺夫变换() 要得到抛物线分布,只需使用0..1范围内的均匀随机生成器并应用平方根。示例应生成范围为0..100的值,靠近端点的密度更大
for (let i = 0; i < 20; i++) {
let x = Math.floor(50 * (Math.pow(Math.Random(), 0.5));
if (Math.Random() < 0.5)
x = 50 - x
else
x = 50 + x;
...
}
for(设i=0;i<20;i++){
设x=Math.floor(50*(Math.pow(Math.Random(),0.5));
if(Math.Random()<0.5)
x=50-x
其他的
x=50+x;
...
}
event尽管@MBo拒绝了我的编辑(但有正确的答案),我仍将分享一个基于最小和最大变量(仅正数)的工作示例
const max=200;
for(设i=0;i<20;i++){
常数min=40;
const focus=0.4;//0-1,越低越关注限制
让numbs=[];
//核心功能
函数随机聚焦边界(最大值、最小值){
常数中间=(最大-最小)/2;
设x=Math.floor(50*(Math.pow(Math.Random(),0.5));
设x=Math.floor(middle*Math.pow(Math.random(),focus));
if(Math.Random()<0.5)
如果(Math.random()<0.5)x=middle-x;
x=50-x
否则x=中间+x;
x+=min;
返回x;
}
其他的
//调用它100次并为numbs数组添加值
x=50+x;
for(设i=0;i<100;i++){
推(随机聚焦边界(最大,最小));
}
//数组升序排序
...
numbs.sort((a,b)=>{
返回a>b?1:-1;
}
});
控制台日志(numbs);
工作很好的方法,感谢斯米尔诺夫的变换。它正接近解决方案,但是,我只寻找正数,而且,这只有一个限制输入,然后根据限制输入将其反转。不过,感谢这种很酷的方法!我添加了范围移位,以获得0..100范围,最小值为50Thanks,如果可以的话,我对你的答案做了一些修改。顺便说一句,如果重点应该更多地放在一端,例如,最小值,你会怎么做?
for (let i = 0; i < 20; i++) {
let x = Math.floor(50 * (Math.pow(Math.Random(), 0.5));
if (Math.Random() < 0.5)
x = 50 - x
else
x = 50 + x;
...
}
const max = 200;
for (let i = 0; i < 20; i++) {
const min = 40;
const focus = 0.4; // 0 - 1, the lower the more focus on limitations
let numbs = [];
//The core function
function randomFocusBorders(max, min) {
const middle = (max - min) / 2;
let x = Math.floor(50 * (Math.pow(Math.Random(), 0.5));
let x = Math.floor(middle * Math.pow(Math.random(), focus));
if (Math.Random() < 0.5)
if (Math.random() < 0.5) x = middle - x;
x = 50 - x
else x = middle + x;
x += min;
return x;
}
else
//Call it 100 times and add value to numbs array
x = 50 + x;
for (let i = 0; i < 100; i++) {
numbs.push(randomFocusBorders(max, min));
}
//Sort numbs array ascending
...
numbs.sort((a, b) => {
return a > b ? 1 : -1;
}
});
console.log(numbs);