python代码转R语言代码#Import required libraries import randomimport numpy as npimport matplotlibpyplot as plt#Coin flip function #0 -- Heads#1 -- Tailsdef coin_flip return randomrandint01 #Check the r
#Import required libraries : library(ggplot2)
#Coin flip function : coin_flip <- function(){ return(sample(c(0,1),1)) }
#Check the return value of coin_flip() : coin_flip()
#Monte Carlo Simulation :
#Empty list to store the probability values. list1 <- c()
monte_carlo <- function(n){ results <- 0 for (i in 1:n){ flip_result <- coin_flip() results <- results + flip_result
#Calculating probability value :
prob_value <- results/(i)
#Append the probability values to the list :
list1 <- c(list1,prob_value)
#Plot the results :
plot <- ggplot() +
geom_hline(yintercept = 0.5, color = 'red', linetype = 'solid') +
xlab("Iterations") +
ylab("Probability") +
geom_line(aes(x=1:length(list1),y=list1)) +
theme_classic()
print(plot)
} return(results/n) }
#Calling the function : answer <- monte_carlo(5000) print(paste("Final value :",answer))
原文地址: https://www.cveoy.top/t/topic/bgbo 著作权归作者所有。请勿转载和采集!