Monday, July 8, 2013

Random Number

This time i would like to discuss/share about algorithm for random number between two range number [ -X, X ]...

Example
  • case 1 : -4 <= X <=4 -> [ -4 , 4 ], or
  • case 2 : -4<= X <=8 -> [ -4 , 8 ]

For case 1, we can solve it by using this method...


Almost all people use this method for solve this problem.

Now, i will show you another method that we can use:

2nd Method :


or,

3th Method :


However, this 3 algorithm only can solve for case 1 problem [ -X , X ].

then, we need little improvement for 2nd Method for solve case 2 [ X , Y] ,

  • (random()*2-1)*n -----------> Open the Bracket 
  • random()*2*n-n    -----------> Conclude 2*n = n1 + n2 and n1 =n2, 
  • ramdom()*(y-x)+x -----------> let n1 =  y , n2 = -x => ( y - x ) 

and it should be look like this.




so now we can try compile and run and check the output/result.

RandomNumber.java :




Sample Running :

Input value of X : 5
How many iteration : 20

rand1(X) rand2(X) rand3(X) rand1(X,Y)
======== ======== ======== ==========
-3.4070 -0.5091 2.6541 0.2463
-0.4505 4.9712 -2.6127 1.2806
0.8037 3.0052 4.0269 1.1330
-0.4072 0.8254 -3.6243 1.8207
3.3936 0.3666 3.1483 4.7780
2.5095 -1.3039 2.9720 -4.3550
-2.2604 3.7140 3.9398 -0.8571
-2.3259 -4.9027 2.1102 -2.5468
-1.1665 -0.2371 1.5750 -0.6682
-3.8450 -2.8542 1.1978 3.9972
4.1191 -1.3540 -2.5854 -0.3069
-4.6430 1.6169 -4.3107 -4.8705
0.0424 -3.6258 0.7341 4.3510
-1.4275 -3.4055 4.8790 2.6856
-1.8183 2.0965 4.1545 0.2370
-1.6285 4.0854 1.3551 -3.3868
-1.3861 1.6281 -4.7341 -0.6756
-0.1027 3.6177 -1.7759 3.6920
-1.5525 -2.0737 -4.6842 3.3273
0.3303 -2.7466 -1.7044 0.2151
======== ======== ======== ==========
rand1(X) rand2(X) rand3(X) rand1(X,Y)








you can test it by your self..
i hope you like this souce code...
and please give some comment....
                                                                                                                                                      Created By : Z-man, 2013

No comments:

Post a Comment