在两个设定数字之间生成随机值

在两个设定数字之间生成随机值

本文介绍了在两个设定数字之间生成随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是在-2到5之间生成5000个随机数然后计算这些值中有多少在2到3之间这是我到目前为止的内容:

My task is to generate 5000 random numbers between -2 and 5then count up how many of those values are between 2 and 3This is what I have so far:

randNums=rand(1,5000); %Generate 5000 random values between 0 and 1

randNums=randNums*7-2; %Get those random values to be between -2 and 5

我理解7*1=70*7=0分别是= 2-2的-2,但是我确实完全理解如果数字在5,6或-6与1之间时如何再次应用.

I understand that 7*1=7 and 0*7=0 so -2 from each = 7-2, but I do nut fully understand how to apply that again if the numbers were to be between 5,6 or -6 and 1.

推荐答案

我的问题解释

您在(0,1)间隔中有随机数.但是,您需要在(a,b)中使用随机数.

My problem interpretation

You have random numbers in the interval (0,1). But you require random numbers in (a,b).

您只需要缩放和移动间隔即可.

You simply have to scale and shift your interval.

缩放间隔:间隔(a,b)的大小/长度为b-a.要重新调整间隔,您必须将所有随机值乘以b-a.

Scale the interval:The size/length of the interval (a,b) is b-a. To rescale the interval you have to multiply all your random values with b-a.

更改时间间隔:缩放间隔后,将在间隔(0,b-a)中包含数字.您只需在数字上加上数字a即可对所有数字进行移位.导致在(a,b)区间中出现随机数.

Shift the interval:When you have scaled the interval you have numbers in the interval (0,b-a). You simply shift all numbers by adding the number a to it. Which leads to random numbers in the interval (a,b).

这篇关于在两个设定数字之间生成随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 16:27