Home >Java >javaTutorial >Detailed explanation of examples of random function transformation in Java

Detailed explanation of examples of random function transformation in Java

WBOY
WBOYforward
2022-08-24 11:59:021865browse

This article brings you relevant knowledge about java, which mainly introduces the transformation of random functions in Java. The sample code in the article is explained in detail, which is helpful for us to learn Java. Those who are interested can learn more.

Detailed explanation of examples of random function transformation in Java

Recommended study: "java video tutorial"

solved problems

Question 1

In Java, the Math.random() function returns any decimal in the interval [0,1) with equal probability. That is, in the case of x < 1, the probability of the number in [0,x) appearing is x. If we want to change x < In the case of 1, the probability of the number in [0,x) is adjusted to x^2. What should be done?

Question 1 Idea

Since the probability of [0,x) is x, then call Math.random()# twice ##, if the larger value is also within the [0,x) interval, then both calls must be within the [0,x) interval (because any In [x,1), the return value will not be on [0,x)), that is, the probability is x^2, the code is as follows

package snippet;

public class Code_0004_RandToPow2 {
    // 将`[0,x)`中的数出现的的概率调整成`x^2`
    public static double randToPow2() {
        return Math.max(Math.random(), Math.random());
    }
}

We can verify the solution to question 1 through the following test code:

package snippet;

public class Code_0004_RandToPow2 {
    // 将`[0,x)`中的数出现的的概率调整成`x^2`
    public static double randToPow2() {
        return Math.max(Math.random(), Math.random());
    }

    // 测试用例
    public static void main(String[] args) {
        int count = 0;
        int testTimes = 10000000;
        double x = 0.17;
        for (int i = 0; i < testTimes; i++) {
            if (randToPow2() < x) {
                count++;
            }
        }
        System.out.println((double) count / (double) testTimes);
        System.out.println(Math.pow(x, 2));
    }
}

The printed results are as follows

0.0288603

0.028900000000000006

Close to target requirements.

Question 2

Suppose we have a random function

f(). This function can return one of [1,5] with equal probability. Number, how to only use the f() function without introducing other random functions to get a function that returns any number in [1,7] with equal probability g().

Idea

Since the goal is to return

[1,7] with equal probability, if we can process a x() function, This function returns any number within the range of [0,6] with equal probability, then the target function g() only needs to call this x() function Adding 1, that is, the g() function requires

public static int g() {
    return x() + 1;
}

to get

[0,6] and return a number with equal probability, we need to first To get a random function m() that returns 0 and 1 with equal probability, we can get it through the f() function, that is,

// 通过[0,5]等概率返回的随机函数f()
// 加工出等概率得到0和1
// 1,2,3,4,5 五个数
// 得到1,2的时候,返回0
// 得到4,5的时候,返回1
// 得到3的时候,弃而不用,再次尝试
    public static int m() {
        int ans = 0;
        do {
            ans = f();
        } while (ans == 3);
        return ans < 3 ? 0 : 1;
    }

is there A random function

m() that returns 0 and 1 with equal probability, we can easily generate a [0,6] method that returns a number with equal probability, because [ 0,6] requires three binary numbers to represent, then we can call the m() function three times, and we can get any number in the range of [0,7] with equal probability , we can retry the above process when we get 7, and only the result will be returned when [0,6], thus processing the x() function.

    // 等概率返回0~6
    public static int x() {
        int ans = 0;
        do {
            ans = (m() << 2) + (m() << 1) + m();
        } while (ans == 7);
        return ans;
    }

Finally, the target function

f() can be obtained as follows

    // 等概率返回1~7
    public static int g() {
        return x() + 1;
    }

. The complete code is as follows

package snippet;

public class Code_0005_Rand5ToRand7 {

    // 此函数只能用,不能修改
    // 等概率返回1~5
    public static int f() {
        return (int) (Math.random() * 5) + 1;
    }

    // 通过[0,5]等概率返回的随机函数f()
// 加工出等概率得到0和1
// 1,2,3,4,5 五个数
// 得到1,2的时候,返回0
// 得到4,5的时候,返回1
// 得到3的时候,弃而不用,再次尝试
    public static int m() {
        int ans = 0;
        do {
            ans = f();
        } while (ans == 3);
        return ans < 3 ? 0 : 1;
    }

    // 等概率返回0~6
    public static int x() {
        int ans = 0;
        do {
            ans = (m() << 2) + (m() << 1) + m();
        } while (ans == 7);
        return ans;
    }

    // 等概率返回1~7
    public static int g() {
        return x() + 1;
    }

    
}

Question 3

has the same idea as Question 2. The core is

We must first implement a method that returns 0 and 1 with equal probability. Random function m(). , and then look at how many binary bits are needed in the target function interval to decide how many times to call the m() function. I won’t go into details. For the complete code, see

/**
 * The rand7() API is already defined in the parent class SolBase.
 * public int rand7();
 * @return a random integer in the range 1 to 7
 */
class Solution extends SolBase {
    public int rand10() {
        return rand(10);
    }

    public int rand(int N) {
        int bit = 1;
        int base = 2;
        while (base <= N) {
            base = 2 << bit;
            bit++;
        }
        int v = build(bit);
        while (v < 1 || v > N) {
            v = build(bit);
        }
        return v;
    }

    private int build(int bit) {
        int v = 0;
        for (int i = 0; i < bit; i++) {
            v += (m() << i);
        }
        return v;
    }

    // 核心:生成 0 和 1 等概率返回的随机函数
    public int m() {
        int i = rand7();
        while (i == 7) {
            i = rand7();
        }
        return (i == 1 || i == 2 || i == 3) ? 0 : 1;
    }
}

Question 4

There is a function

f(), which returns 0 and 1 with unequal probability (but fixed probability). How to get equal probability of returning 0 and 1 only through the f() function? Random function g(),

idea,

call the

f() function twice, you can get the following situation

0 0

1 1
0 1
1 0

When both times are 0, or both times are 1, discard it, although 0 The probability is different from 1, but the probability of

0 1

1 0

must be the same

so we get

0 1Return 0, get 1 0Return 1, that is, g()function

The complete code is as follows

package snippet;

// 不等概率随机函数变成等概率随机函数
public class Code_0005_EqualProbabilityRandom {

    // 不等概率函数,
    // 内部内容不可见
    public static int f() {
        return Math.random() < 0.8 ? 0 : 1;
    }

    // 等概率返回0和1
    public static int g() {
        int first;
        do {
            first = f(); // 0 1
        } while (first == f());
        return first;
    }

}

Recommended learning: "

java video tutorial

The above is the detailed content of Detailed explanation of examples of random function transformation in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete