Pages

Thursday 24 July 2014

The maths of Texas Hold ’em with R

Please before continue reading, make sure to read the disclaimer at the bottom of this article.

Every time I watch on tv some game of Texas Hold’em I am always curious about the small percentages which appear in the bottom corners of the screen and tell us the chances of win for each player. There must be some kind of algorithm which implements and refreshes those numbers at each draw.

Today I am going to write about one of the first simulations I put down as code and wrapped my head around. Now that I am a little smarter at coding than I was when I coded this, I believe this whole simulation could be done much better and with A LOT less code… Anyway I guess that is a good sign since the fact I found “mistakes” in my code should mean I improved at least on the very things I made mistakes on.

The code I am about to show estimates the probabilities of drawing a pair, a three of a kind (tris) and a poker.

Let’s proceed, first of all: we need to define the deck and the drawing function.

Let’s try our drawing function hand() and check the result:

im2



Not that good draw we were looking for huh? Anyway that’s a complete game of Texas Hold’em (provided neither of the two player folded).



Why don’t we create 100 of these games? Here they are:

At this stage, if we run the code, R will generate three tables (or matrix) with the results of each one of the 100 simulate games. Something like this:



games



Now we need only to look for pairs, tris and pokers. We need to define 3 functions as follows:

The result should look like this:

im5



In 100 games, we have got 47 pairs, 2 three of a kind and no pokers! Interesting data! However, this might be a mere case! We need to run this a LOT of times to be sure the odds we obtained are at least near the real ones. Let’s build a function that can do this. For instance, the function below runs n times 100 games and then collect the results. Note that It outputs the probabilities as the mean of the probabilities occurred. Much of the code here is replicated from the functions above. I guess this could have been done a lot better! If you have any idea please let me know or leave a comment!

Let’s try for instance to run this 10.000 times, with n = 100. Here are the results:



Immagine 9



Immagine 7



For debugging purposes our function outputs each poker it finds. Since usually pokers are not that frequent it should be fine. 10.000 times seems not to be enough…
Let’s do 100.000 times!!!



Immagine 8



This looks better! By simulating in less than 2 minutes 100.000 games of Texas Hold’em with 2 players we concluded that drawing a poker two times in a row is a very unlikely event, drawing a pair is a relative common event while three of a kind is rare, but not as much as poker!



I should mention that, it looks like the probability of a poker is overestimated according to the formal calculation, I believe that is either because it is an “outlier” or because I did not run the simulation a big enough number of times. Anyway the other two probabilities seem fine (you can check for more information on http://en.wikipedia.org/wiki/Poker_probability)



Hope you enjoyed!








Disclaimer: This article is for educational purpose ONLY. Odds generated by this code are calculated by a random simulation. As such the odds will represent an approximation of the true odds. They might even be completely wrong or misleading. This code must NOT be used for anything other than educational purpose. The provider of this code does not guarantee the accuracy of the results and accepts no liability for any loss or damage that may occur as a result of the use of this code. Understanding and agreeing to the terms of this disclaimer is a condition of use of this code. By reading the article you confirm you have understood and will comply with this disclaimer.

14 comments:

  1. By "tris" and "pokers" do you mean "trips" (3 of a kind) and "quads" (4 of a kind)? The name "poker" doesn't refer to any configuration of cards (http://www.todayifoundout.com/index.php/2012/08/how-the-game-poker-got-its-name/).

    Thank you for your post though, I feel encouraged to start writing a poker-odds package in R now.

    ReplyDelete
    Replies
    1. Also, your odds of getting a pair or trips should exclude the odds of getting a better hand that you're counting;

      p1_pairs_test = (p1_has_pair) & (!p1_has_trips) & (!p1_has_quads)

      Delete
  2. Hi JonoCarroll, thanks for your comment.

    Yes by 'tris' and 'poker' I mean, respectively, three of a kind and four of a kind (dealer's cards plus your cards). My friends use those names :), thanks for pointing out the correct ones.

    As for the odds, having a 'trips' or a 'quads' implies that you have (at least) a pair. A better label for my calculation would be 'a pair or better' (assuming no flushes or other higher scores are considered aside from these 3 scores I considered), a bit of semplification is always welcomed :) . While what you suggested I guess could be labeled as '(strictly) a pair'.

    I'm glad this post encouraged you to write your own R package. Leave a comment with the GitHub link if you put your package on GitHub.

    ReplyDelete
  3. Cheap web hosting for small businesses offers a budget-friendly yet reliable solution to establish an online presence. These hosting services provide essential features like ample storage, bandwidth, and excellent uptime, ensuring your website runs smoothly. Most affordable plans include intuitive website builders and professional templates, making site creation hassle-free. Security features such as SSL certificates and automated backups protect your site from threats. Many providers offer scalable plans, which can grow with your business needs. Integrated email hosting solutions streamline your online operations. With responsive customer support, small businesses can resolve issues quickly. In essence, cheap web hosting empowers small businesses to compete in the digital marketplace without high costs.
    https://onohosting.com/

    ReplyDelete
  4. Transitioning from India to Australia as a registered nurse requires a systematic approach. Start by earning a Bachelor of Nursing degree recognized by the Australian Nursing and Midwifery Accreditation Council (ANMAC). Next, apply for registration with the Australian Health Practitioner Regulation Agency (AHPRA), ensuring you meet their English proficiency standards, including a minimum score of 7 in each band of the IELTS exam. Gain one to two years of relevant clinical experience, and complete mandatory criminal history checks in both India and Australia. Pass a comprehensive health examination and, if required, the Objective Structured Clinical Examination (OSCE) or a similar assessment. Secure a visa, such as the Skilled Independent Visa (subclass 189) or the Skilled Nominated Visa (subclass 190). Finally, begin your job search using Australian job portals, healthcare networks, and international recruitment agencies, tailoring your resume and cover letter to Australian standards.
    https://dynamichealthstaff.com/nursing-jobs-in-australia-for-indian-nurses

    ReplyDelete
  5. Breast cancer treatment in Delhi encompasses a range of procedures and services, each with its associated costs. The overall expense can vary significantly depending on the type and stage of cancer, the treatment plan recommended by oncologists, and the specific healthcare facility. On average, the cost of breast cancer treatment in Delhi might include surgery (ranging from ₹2,00,000 to ₹4,50,000), chemotherapy sessions (₹20,000 to ₹1,00,000 per session), and radiation therapy (between ₹1,50,000 and ₹4,00,000). Additionally, targeted therapy and immunotherapy can add to the overall cost, potentially making the total expenditure range from ₹5,00,000 to ₹20,00,000 or more. It is crucial for patients to consult with their healthcare providers and explore various financial assistance programs and insurance options to manage these costs effectively.
    https://www.breastoncosurgery.com/services/breast-cancer-treatment-cost-in-delhi/

    ReplyDelete
  6. Colon cancer treatment in Ahmedabad offers various advanced medical options tailored to individual patient needs. The primary treatments include surgery, which can cost between ₹1,50,000 and ₹3,50,000, depending on the extent of the procedure and the facility chosen. Chemotherapy sessions generally range from ₹50,000 to ₹1,20,000 per cycle, with the total cost influenced by the specific drugs and protocols used. Radiation therapy expenses typically fall within ₹70,000 to ₹1,50,000 for a complete course. Emerging treatments like targeted therapy and immunotherapy can be substantially more costly, ranging from ₹1,00,000 to ₹4,00,000 per cycle. Government hospitals in Ahmedabad provide more affordable treatment options, while private hospitals offer personalized care packages. Consulting with healthcare professionals is essential for selecting the most effective and budget-friendly treatment plan tailored to one's medical needs.
    https://drvirajlavingia.com/colorectal-cancer-specialist-in-ahmedabad

    ReplyDelete
  7. Mumbai is home to some of the leading breast cancer doctors, renowned for their specialized expertise and compassionate care. These medical professionals are skilled in diagnosing and treating breast cancer at all stages, employing the latest technologies such as digital mammography, MRI, and advanced biopsy techniques. Working within state-of-the-art facilities, they offer a multidisciplinary approach that includes surgery, chemotherapy, radiation, and targeted therapies. Their dedication to patient well-being extends beyond treatment, providing personalized care plans and robust support systems for physical and emotional recovery. Continuous professional development ensures they remain at the cutting edge of oncological advancements. Patients seeking expert breast cancer treatment in Mumbai can trust these physicians for comprehensive and empathetic care.
    https://drnitanair.com/about/about-top-breast-cancer-surgeon-mumbai

    ReplyDelete
  8. Dr. Shona Nag is a highly skilled breast cancer surgeon based in Pune, recognized for her specialization in oncology and advanced surgical techniques. With a focus on personalized care, she utilizes cutting-edge diagnostic tools to tailor treatment plans for each patient. Dr. Nag collaborates closely with premier hospitals and cancer centers in Pune, ensuring comprehensive and empathetic patient management. Known for her precision and dedication, she provides steadfast support to patients and their families throughout their cancer journey. Actively contributing to breast cancer research and education, Dr. Nag strives to enhance treatment outcomes and improve patient quality of life. Her commitment to clinical excellence establishes her as a respected leader in breast cancer surgery in Pune and beyond.
    https://www.drshonanagbreastcancer.in/understanding-cancer/what-is-cancer-can-cancer-be-cured

    ReplyDelete
  9. Mobile App Development Company in Delhi is a premier provider of bespoke mobile solutions designed to elevate businesses across various industries. With a talented team of developers and designers, they specialise in creating intuitive applications for both Android and iOS platforms. The company employs the latest technologies and innovative practices to ensure that each app not only meets client specifications but also captivates users. They focus on user-centric designs that enhance engagement and satisfaction, while rigorous quality assurance ensures top-notch performance. Additionally, comprehensive post-launch support keeps applications updated and competitive in a fast-paced digital environment. By prioritising client needs and market trends, they help businesses navigate the complexities of mobile technology. Trust Mobile App Development Company in Delhi to turn your ideas into impactful mobile experiences. Experience unparalleled service and creativity with their expert team at your side.
    https://olycoder.com/mobile-app-development-company

    ReplyDelete
  10. Minoxidil for women in Australia is a clinically proven treatment designed to combat hair loss and promote regrowth. Specifically formulated to address female pattern baldness, it works by revitalizing hair follicles and enhancing blood circulation to the scalp. This easy-to-use topical solution is available in both liquid and foam forms, making it simple to integrate into your daily routine. Many women see visible results within a few months of consistent application, helping to restore confidence and self-esteem. Dermatologically tested for safety, Minoxidil is suitable for various hair types and concerns. With its effective formulation, this treatment empowers women to take control of their hair health. Experience thicker, fuller hair and embrace your natural beauty with Minoxidil. Trust in a reliable solution that has been embraced by countless women across Australia.
    https://generichealth.com.au/minoxidil-hair-loss/

    ReplyDelete
  11. Advocate Rajkumar Solanki is a distinguished legal practitioner based in Delhi, renowned for his expertise and commitment to handling complex family law cases. With over two decades of experience, he combines strategic acumen with a compassionate approach to serve his clients effectively. Specializing in divorce and custody matters, Advocate Solanki is adept at both negotiation and litigation. His deep understanding of Delhi's legal framework ensures tailored solutions to clients' specific needs. Known for his clear and honest communication, he builds trust while easing the emotional stress of legal proceedings. Advocate Solanki's dedication to achieving fair outcomes has earned him a strong reputation and a loyal client base. His proactive and empathetic demeanor makes him a sought-after advocate for individuals seeking reliable legal support in family matters.
    https://bestdivorcelawyerindelhi.com/

    ReplyDelete