Detailed explanation of examples of random function transformation in Java
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.
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 , the probability of the number in <code>[0,x)
appearing is x
. If we want to change x , the probability of the number in <code>[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.0288603Close to target requirements. Question 2 Suppose we have a random function0.028900000000000006
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().
[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
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 4There 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(),
f() function twice, you can get the following situation
0 0When both times are 0, or both times are 1, discard it, although 0 The probability is different from 1, but the probability of1 1
0 1
1 0
0 1must be the sameso we get1 0
0 1Return 0, get
1 0Return 1, that is,
g()function
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!

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

JRE is the environment in which Java applications run, and its function is to enable Java programs to run on different operating systems without recompiling. The working principle of JRE includes JVM executing bytecode, class library provides predefined classes and methods, configuration files and resource files to set up the running environment.

JVM ensures efficient Java programs run through automatic memory management and garbage collection. 1) Memory allocation: Allocate memory in the heap for new objects. 2) Reference count: Track object references and detect garbage. 3) Garbage recycling: Use the tag-clear, tag-tidy or copy algorithm to recycle objects that are no longer referenced.

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor