问题描述:有一个函数,可以等概率的生成x∈(a,b),如何编写函数生成x∈(c,d)
举例f函数可以生成[1,5],生成[1,7]
1 public static int f() { 2 return (int) (Math.random() * 5) + 1; 3 }
解题思路:
- 通过f()改造成等概率的0和1函数f1()
- 通过f1()生成f2()∈[0,7],借用二进制思路
- 通过f2()生成f3()∈[0,6]
- f3()+1即可
f1()的实现:
f(x)∈[1, 2, 3, 4, 5]
f1(x) = 0 when x = 1 or 2
f1(x) = 1 when x = 4 or 5
f1(x)重新计算 when x = 3
1 public static int f1() { 2 3 int result = f(); 4 5 while (result == 3) { 6 result = f(); 7 } 8 9 if (result == 1 || result == 2) { 10 return 0; 11 } else { 12 return 1; 13 } 14 }
通过01二进制实现[0,7]
000 = 0 001 = 1 010 = 2 ... 111 = 7
1 public static int f2() { 2 return (f1() << 2) + (f1() << 1) + f1(); 3 }
x∈[0,5], f2(x)∈[0,7],当f(x)=7的时候在重新计算,就完成了[0,6]
public static int f3() {int result = f2();while (result == 7) {result = f2();}return result;}
[0,6]+1=[1,7]
public static int f4() {int result = f3();return result + 1;}