Home
About
Blog
Products
Forum
Support
Contact
Sunbelt Computer Software
PL/B Language Development and Support
Home
About
Blog
Products
Forum
Support
Contact
Python/maths/monte_carlo.py at Python-3.9rc2 · davgit/Python · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
Platform
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
Solutions
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
Resources
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
Open Source
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
Enterprise
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Search
/
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
davgit
/
Python
Public
forked from
TheAlgorithms/Python
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Files
Expand file tree
Python-3.9rc2
Breadcrumbs
Python
/
maths
/
monte_carlo.py
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
129 lines (110 loc) · 4.46 KB
Python-3.9rc2
Breadcrumbs
Python
/
maths
/
monte_carlo.py
Copy path
Top
File metadata and controls
Code
Blame
129 lines (110 loc) · 4.46 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
"""
@author: MatteoRaso
"""
from
math
import
pi
,
sqrt
from
random
import
uniform
from
statistics
import
mean
from
typing
import
Callable
def
pi_estimator
(
iterations
:
int
):
"""
An implementation of the Monte Carlo method used to find pi.
1. Draw a 2x2 square centred at (0,0).
2. Inscribe a circle within the square.
3. For each iteration, place a dot anywhere in the square.
a. Record the number of dots within the circle.
4. After all the dots are placed, divide the dots in the circle by the total.
5. Multiply this value by 4 to get your estimate of pi.
6. Print the estimated and numpy value of pi
"""
# A local function to see if a dot lands in the circle.
def
is_in_circle
(
x
:
float
,
y
:
float
)
->
bool
:
distance_from_centre
=
sqrt
((
x
**
2
)
+
(
y
**
2
))
# Our circle has a radius of 1, so a distance
# greater than 1 would land outside the circle.
return
distance_from_centre
<=
1
# The proportion of guesses that landed in the circle
proportion
=
mean
(
int
(
is_in_circle
(
uniform
(
-
1.0
,
1.0
),
uniform
(
-
1.0
,
1.0
)))
for
_
in
range
(
iterations
)
)
# The ratio of the area for circle to square is pi/4.
pi_estimate
=
proportion
*
4
print
(
f"The estimated value of pi is
{
pi_estimate
}
"
)
print
(
f"The numpy value of pi is
{
pi
}
"
)
print
(
f"The total error is
{
abs
(
pi
-
pi_estimate
)
}
"
)
def
area_under_curve_estimator
(
iterations
:
int
,
function_to_integrate
:
Callable
[[
float
],
float
],
min_value
:
float
=
0.0
,
max_value
:
float
=
1.0
,
)
->
float
:
"""
An implementation of the Monte Carlo method to find area under
a single variable non-negative real-valued continuous function,
say f(x), where x lies within a continuous bounded interval,
say [min_value, max_value], where min_value and max_value are
finite numbers
1. Let x be a uniformly distributed random variable between min_value to
max_value
2. Expected value of f(x) =
(integrate f(x) from min_value to max_value)/(max_value - min_value)
3. Finding expected value of f(x):
a. Repeatedly draw x from uniform distribution
b. Evaluate f(x) at each of the drawn x values
c. Expected value = average of the function evaluations
4. Estimated value of integral = Expected value * (max_value - min_value)
5. Returns estimated value
"""
return
mean
(
function_to_integrate
(
uniform
(
min_value
,
max_value
))
for
_
in
range
(
iterations
)
)
*
(
max_value
-
min_value
)
def
area_under_line_estimator_check
(
iterations
:
int
,
min_value
:
float
=
0.0
,
max_value
:
float
=
1.0
)
->
None
:
"""
Checks estimation error for area_under_curve_estimator function
for f(x) = x where x lies within min_value to max_value
1. Calls "area_under_curve_estimator" function
2. Compares with the expected value
3. Prints estimated, expected and error value
"""
def
identity_function
(
x
:
float
)
->
float
:
"""
Represents identity function
>>> [function_to_integrate(x) for x in [-2.0, -1.0, 0.0, 1.0, 2.0]]
[-2.0, -1.0, 0.0, 1.0, 2.0]
"""
return
x
estimated_value
=
area_under_curve_estimator
(
iterations
,
identity_function
,
min_value
,
max_value
)
expected_value
=
(
max_value
*
max_value
-
min_value
*
min_value
)
/
2
print
(
"******************"
)
print
(
f"Estimating area under y=x where x varies from
{
min_value
}
to
{
max_value
}
"
)
print
(
f"Estimated value is
{
estimated_value
}
"
)
print
(
f"Expected value is
{
expected_value
}
"
)
print
(
f"Total error is
{
abs
(
estimated_value
-
expected_value
)
}
"
)
print
(
"******************"
)
def
pi_estimator_using_area_under_curve
(
iterations
:
int
)
->
None
:
"""
Area under curve y = sqrt(4 - x^2) where x lies in 0 to 2 is equal to pi
"""
def
function_to_integrate
(
x
:
float
)
->
float
:
"""
Represents semi-circle with radius 2
>>> [function_to_integrate(x) for x in [-2.0, 0.0, 2.0]]
[0.0, 2.0, 0.0]
"""
return
sqrt
(
4.0
-
x
*
x
)
estimated_value
=
area_under_curve_estimator
(
iterations
,
function_to_integrate
,
0.0
,
2.0
)
print
(
"******************"
)
print
(
"Estimating pi using area_under_curve_estimator"
)
print
(
f"Estimated value is
{
estimated_value
}
"
)
print
(
f"Expected value is
{
pi
}
"
)
print
(
f"Total error is
{
abs
(
estimated_value
-
pi
)
}
"
)
print
(
"******************"
)
if
__name__
==
"__main__"
:
import
doctest
doctest
.
testmod
()
You can’t perform that action at this time.