DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Tips and Tricks for Efficient Coding in R
  • How to Get a Non-Programmer Started with R
  • Python vs. R: A Comparison of Machine Learning in the Medical Industry
  • How to Rectify R Package Error in Android Studio

Trending

  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Docker Base Images Demystified: A Practical Guide
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  • Unlocking the Benefits of a Private API in AWS API Gateway
  1. DZone
  2. Coding
  3. Languages
  4. Simulation of Gambler's Ruin (Random Walk) With R

Simulation of Gambler's Ruin (Random Walk) With R

In this article, I will simulate the Gambler's Ruin problem with R with different settings and examine how the game results change with these different settings.

By 
Emrah Mete user avatar
Emrah Mete
·
Feb. 08, 18 · Analysis
Likes (6)
Comment
Save
Tweet
Share
11.2K Views

Join the DZone community and get the full member experience.

Join For Free

The Gambler's Ruin problem is one of the most researched topics in the field of operational research.

Let's consider a game where a gambler is likely to win $1 with a probability of p and lose $1 with a probability of 1-p.

Now, let's consider a game where a gambler is likely to win $1 and lose $1 with a probability of 1. The player starts the game with X dollars in hand. The player plays the game until the money in his hand reaches N (N> X) or he has no money left. What is the probability that the player will reach the target value? (We know that the player will not leave the game until he reaches the N value he wants to win.)

The problem of the story above is known in literature as Gambler's Ruin or Random Walk. In this article, I will simulate this problem with R with different settings and examine how the game results change with different settings.

I will use these parameters while doing this simulation:

  • The money that the player holds when he enters the game.
  • The lower limit of the game.
  • The upper limit of the game.
  • The probability that the player earns $1 (P).
  • We repeat the experiment with the above parameters (n).

Now, let's create a few scenarios from the parameters we have defined and simulate them with these scenarios.

Use Case 1

  • The money that the player holds when he enters the game: $6
  • The lower limit of the game: $2
  • The upper limit of the game: $10
  • The probability that the player earns $1: p: 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9
    • We will play the game separately for each probability value.
  • We repeat the experiment with the above parameters (n): 100

Use Case 2

  • The money that the player holds when he enters the game: $10
  • The lower limit of the game: $1
  • The upper limit of the game :$10
  • The probability that the player earns $1: p: 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9
    • We will play the game separately for each probability value.
  • We repeat the experiment with the above parameters (n): 100

Use Case 3

  • The money that the player holds when he enters the game: $10
  • The lower limit of the game is: $3
  • The upper limit of the game: $20
  • The probability that the player earns $1: p: 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9
    • We will play the game separately for each probability value.
  • We repeat the experiment with the above parameters (n): 100

We have three basic scenarios described above. However, since we will run the same scenario again and again for different probability values (nine), each scenario will run nine times in total. At the end of the day, we will run 9*3 = 27 different scenarios.

Now, let's go to the R co:e to simulate. I will write a total of five functions to complete this simulation. These are;

  • ReadInstances: With this function, I read the amount of money in the player's hand and the upper and lower limit of the game through the .txt files.

    • Sample file format (current, lower limit, upper limit): 6, 2, 10

  • GamblerRun: A function that plays once with given the parameters and returns the result (win/loss).

  • Simulator: The GamblerRuin function runs for as many possible scenarios as possible and records the results.

  • ExportResults: The function that writes the simulation results to the file.

  • Analyzer: The function that reads and predicts the simulation results written to the file and calculates the error depending on this estimation.

    • Error = |Pactual-Pestimated|/Pactual

Now, we can go to the code writing section in R.

We initialize our variables in the first place.

#Initializing Parameters
instancesFolder = "ProblemInstances"
options(warn = -1)
options(max.print = 100000000)
probabilities = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
n = c(100)

Now, we can start writing the functions.

ReadInstances:

# Function ReadInstances(input FilesFolderPaths)
# Return: DataFrame, each record in seperate files
ReadInstances <- function(instancesFolder) {
  mydata = data.frame()
  files <- as.list(list.files(path = instancesFolder))
  for (i in 1:length(files))
  {
     line <-
          read.csv(
                   paste("ProblemInstances", .Platform$file.sep, files[i], sep = ""),
                   header = F,
                   sep = ",",
                   quote = ""
                  )
        line$UL > line$currentState && line$UL > line$LL)
    {
      mydata = rbind(mydata, line)
    }
  }
  colnames(mydata) = c('currentState', 'LL', 'UL', 'fileName')
  return(as.data.frame(mydata))
}

GamblerRuin (we play the game as a Bernoulli trial and take advantage of the rbinom function to accomplish this):

# Function GamblerRuin(inputs currentState, UL, LL, p)
# Return: string, game result win or lose
GamblerRuin <- function(currentState, UL, LL, p) { while (currentState > LL && currentState < UL)
  {
    coin = rbinom(1, 1, p)

    if (coin == 1)
    {
      currentState = currentState + 1
    }
    else
    {
      currentState = currentState - 1
    }
  }

  if (currentState == UL)
  {
    return("win")
  }
  else  
  {
    return("lose")
  }
}

Simulator:

# Function Simulator(inputs problemInstances, probabilities, n)
# Saving Scenarios and SimulationResults to Files
# Return: data frame, results of all possible scenarios (resultTable)
Simulator <- function(problemInstances, probabilities, n) {
  set.seed(0)
  resultTable = data.frame()
  scenarioID = 0
  scenarioTable = data.frame()

  for (instance in 1:nrow(problemInstances)) {
    for (prob in 1:as.integer(length(probabilities)))
    {
      for (j in 1:as.integer(length(n)))
      {
        scenarioID = scenarioID + 1
        scenrow = data.frame(problemInstances[instance,]$fileName,
                             scenarioID,
                             probabilities[prob],
                             n[j])
        scenarioTable = rbind(scenarioTable, scenrow)

        for (k in 1:n[j])
        {
          gameResult = GamblerRuin(
            problemInstances[instance, ]$currentState,
            problemInstances[instance, ]$UL,
            problemInstances[instance, ]$LL,
            probabilities[prob]
          )
          row = data.frame(problemInstances[instance, ]$fileName,
                           scenarioID,
                           probabilities[prob],
                           n[j],
                           k,
                           gameResult)
          resultTable = rbind(resultTable, row)
        }
      }
    }
    scenarioID = 0
  }


  colnames(scenarioTable) = c('instanceFileName', 'ScenarioID', 'p', 'n')
  #Save Scenario to File
  ExportResults(scenarioTable, "ScenarioFormatted.txt", 2)
  ExportResults(scenarioTable, "Scenario.txt", 1)

  colnames(resultTable) = c('instanceFileName',
                            'ScenarioID',
                            'p',
                            'n',
                            'ReplicationID',
                            'Result')


  SimulationResults <-
    subset(resultTable,
           select = c(instanceFileName, ScenarioID, ReplicationID, Result))
  #Save SimulationResults to File
  ExportResults(SimulationResults, "SimulationResultsFormatted.txt", 2)
  ExportResults(SimulationResults, "SimulationResults.txt", 1)


  return(resultTable)
}

ExportResults:

# Function ExportResults(inputs dataFrame, fileName, type)
# Saving to file (data and filename are parameters)
#type1: standart csv output, type2: formatted output
ExportResults <- function(dataFrame, fileName, type)
{
  #type1: standart csv output
  if (type == 1)
  {
    write.table(
      dataFrame,
      file = fileName,
      append = FALSE,
      quote = TRUE,
      sep = ",",
      eol = "\n",
      na = "NA",
      dec = ".",
      row.names = FALSE,
      col.names = TRUE,
      qmethod = c("escape", "double"),
      fileEncoding = ""
    )

  }
  else
    #type2: formatted output
  {
    capture.output(print(dataFrame, print.gap = 3, row.names = FALSE), file =
                     fileName)
  }
}

ReadFilesFromCsv <- function(fileName)
{
  myData = read.csv(fileName,
                    header = T,
                    sep = ",",
                    quote = "")
  return(myData)
}

Analyzer:

# Function Analyzer()
# Read recorded files and Analysis Estimation Errors
# Saving and Plotting Result of Analysis
Analyzer <- function() {
  #Read Simulation Result
  simulationResults = ReadFilesFromCsv("SimulationResults.txt")

  #converting formatted data frame
  simResults = (data.frame(
    table(
      simulationResults$X.instanceFileName,
      simulationResults$X.ScenarioID,
      simulationResults$X.Result
    )
  ))
  colnames(simResults) = c('instanceFileName', 'ScenarioID', 'Result', 'Count')

  #Seprating "win" and "lose" records to calculating p value.(using external libarary dplyr)
  library(dplyr)
  simResults_win  =  filter(simResults, Result == as.character('"win"'))
  simResults_lose =  filter(simResults, Result == as.character('"lose"'))

  #Join 2 data frame and calculate p_estimated value (using sqldf external libarary)
  library(sqldf)
  simResultsWithPestimated <-
    sqldf(
      "SELECT instanceFileName,ScenarioID,
      round((cast(simResults_win.Count as real)/(simResults_lose.Count+simResults_win.Count)),3) p_estimated
      FROM simResults_win
      JOIN simResults_lose USING(instanceFileName,ScenarioID)"
    )


  #Read Scenario Result
  scenarios = ReadFilesFromCsv("Scenario.txt")

  #changing column name
  colnames(scenarios) = c('instanceFileName', 'ScenarioID', 'p', 'n')


  #Caclulation Percentage Error using sqldf external libarary
  library(sqldf)
  estimationErrors = sqldf(
    "SELECT instanceFileName,ScenarioID,sc.p p_actual, sim.p_estimated p_estimated,
    round(abs(cast(sc.p - sim.p_estimated as real)/ sc.p),3) PercentageError
    FROM scenarios sc
    JOIN simResultsWithPestimated sim USING(instanceFileName,ScenarioID)"
  )

  #dump out staging and final data frames
  ExportResults(simResultsWithPestimated,
                "SimulationResultWithPestimated.txt",
                2)
  ExportResults(estimationErrors, "estimationErrors.txt", 2)

  #plotting estimationErrors vector
  countOfPercentageError <- table(estimationErrors$PercentageError)
  barplot(
    countOfPercentageError,
    main = "Percentage Error Distribution",
    xlab = "ErrorRates",
    ylab = "Number of Counts"
  )

}

We have completed the writing of all our functions. Now, let's write the code snippet to run the simulation and examine the results.

instances = ReadInstances(instancesFolder)
resultTable = Simulator(instances, probabilities, n)
Analyzer()
ExportResults(resultTable, 'ResultTable.txt', 2)

One of the outputs we produced since our code was worked is which scenarios work.

Another output produced is the results of the games played (only a sample set is listed).

The final output produced is the estimated values calculated for each scenario.

In the graph below, we see the distribution of the calculated error.

And that's it!

R (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Tips and Tricks for Efficient Coding in R
  • How to Get a Non-Programmer Started with R
  • Python vs. R: A Comparison of Machine Learning in the Medical Industry
  • How to Rectify R Package Error in Android Studio

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!