Sampling from distributions

Size: px
Start display at page:

Download "Sampling from distributions"

Transcription

1 Sampling from distributions December 17, Sampling from distributions Now that we are able to sample equally distributed (pseudo-)random numbers in the interval [1, 0), we are now able to sample random numbers from arbitrary distributions. 1.1 Setup In [1]: %matplotlib inline import numpy as np import scipy as sp import matplotlib.pyplot as plt 1.2 Rejection sampling The most simple method to generate random numbers from a distribution is called rejection sampling. This method is generally easy to implement, but can be very slow depending on the sampled distribution. Further info can be found at Wikipedia. Assume we want to sample data from a probability density function f. Assume further we are able to genrate random numbers according to a distribution g. Also, we have a bound M, so that f(x) < Mg(x) x. Then we can sample random numbers distributed like f: 1. Sample a random number u [0, 1) 2. Sample a random number x from g(x) 3. Calculate = f(x) Mg(x) u If 0, x is distributed according to f, and we return the random number x. Else, we reject the result and repeat the process. For example, we can use equally distributed random numbers in an interval [a, b], and select an M so that g(x) = 1 x [a, b). In practice, we can just set g(x) = M = 1. So let s write the code to implement what we described above: In [2]: def gauss(x, mu=0., sigma=1.): return 1./(sigma * np.sqrt(2.*numpy.pi)) * np.exp(-0.5 * ( 1.*(x-mu) / sigma)**2) def rejection_sampler(func, a=0., b=1., M=1., *funcargs, **funckwargs): delta = -1 x = 0 while not delta >= 0: # generate uniformly distributed random number in the interval [a, b) x = (b-a) * np.random.random() + a # generate uniformly distributed random number in the interval [0,1] u = np.random.random() * M # calculate delta delta = 1.*func(x, *funcargs, **funckwargs) - u return x def rejection_sampler_example(func, a=0., b=1., M=1., *funcargs, **funckwargs): 1

2 delta = -1 x = 0 # generate uniformly distributed random number in the interval [a, b) x = (b-a) * np.random.random() + a # generate uniformly distributed random number in the interval [0,1] u = np.random.random() * M # calculate delta delta = 1.*func(x, *funcargs, **funckwargs) - u return x, u, delta >= 0 # limit the range of sampling # choosing larger intervals increases computing time due to more rejections x = numpy.arange(-20.,20.,0.01) a = x[0] b = x[-1] M = 0.6 # gaussian distribution does not exceed 0.6 r = numpy.array([rejection_sampler(gauss, a, b, M) for i in xrange(50000)]) r_e = numpy.array([rejection_sampler_example(gauss, a, b, M) for i in xrange(1000)]) # plot the histogram of the sampled numbers h, xb = np.histogram(r, bins=1000, density=true) plot(xb[:-1]+np.diff(xb), h, color= b, label= Rejection sampled normal distribution ); #plot(r_e[:,0][r_e[:,2]==0], r_e[:,1][r_e[:,2]==0],linestyle=, marker= x, color= y ) #plot(r_e[:,0][r_e[:,2]==1], r_e[:,1][r_e[:,2]==1],linestyle=, marker= o, color= r ) # overplot the calculated gauss x = numpy.arange(-6.,6.,0.01) y = gauss(x) plot(x,y, color= r, label= Normal distribution ); # prettify xlabel("x") ylabel("p") ylim(0., 0.7) xlim(-6.,6.) legend(); 2

3 Rejection sampled normal distribution Normal distribution 0.4 p x The algorithm works well, but as we can see is quite slow. The main reason is that on the wings the probability approaches zero fast, which means we reject a lot of random numbers. Every rejection means that we will have to call the function again. Thus, the runtime of this sampling method depends strongly on the similarity of the envelope distribution and the distribution to be sampled, and the chosen interval. 1.3 Inversion sampling The other widespread used method to sample random numbers is inversion sampling. Info on that can also be found at Wikipeda. Assume we want to take random samples distributed like a known continuous distribution function F (x). We have to do the following steps: 1. Normalize F F (x)dx = N, to calculate the probability density function (PDF) f(x) = F (x)/n 2. Calculate the cumulative distribution function (CDF) C(x) = x f(x )dx 3. Calculate the inverse CDF (icdf). This assumes that C(x) can be inverted (i.e. solved for x), so that we get a function X(U) 4. Sample a uniformly distributed random number u in the interval [0, 1) 5. Calculate x = X(u). The generated xs will be distributed according to the probability density function f(x) Let s implement the algorithm and inspect all the steps and generate random numbers according to an exponential distribution. The PDF of an exponential distribution is f(x) = λ exp ( λx), and it s defined on the interval [0, ) In [3]: x = np.arange(0,15,0.001) 3

4 In [4]: def expon(x, l=1.): return l * np.exp(-l * x) plot(x, expon(x), label="exponential distribution PDF"); legend(); Exponential distribution PDF The CDF of the exponential distribution is C(x) = 1 exp ( λx) In [5]: def expon_c(x, l=1.): return 1. - np.exp(-l * x) plot(x, expon_c(x), label="exponential distribution CDF"); legend(); 4

5 Exponential distribution CDF We can see nicely that the cumulative distribution function does not exceed 1. We can already see that if we invert the CDF C(x) and sample values on the y-axis, that we can generate the values on the x-axis. The icdf is X(U) = 1 λ ln (1 U). In [6]: def expon_ic(u, l=1.): return -1./l * np.log(1. - U) u = np.arange(0., 1., 0.001) plot(u, expon_ic(u), label="exponential distribution icdf"); legend(); 5

6 7 6 Exponential distribution icdf We can now write our random number generator, which creates numbers according to the exponential distribution, and try it out. In [7]: def rand_expon(l=1.): u = np.random.random() return expon_ic(u, l) r = np.array([rand_expon() for i in xrange(200000)]) h, xb = np.histogram(r, bins=1000, density=true) plot(xb[:-1]+np.diff(xb), h, color= b, label= Inversion sampled exponential distribution ); plot(x, expon(x), color= r, label= Exponential distribution ); legend(); 6

7 Inversion sampled exponential distribution Exponential distribution Let s compare the runtime of the inversion sampling method, to the runtime of the rejection sampling method. We can already see that it is very impractical to generate random numbers up to using rejection sampling. We compare both methods for different interval lengths. In [8]: import time b= 5.0 def rand_expon_interval(a=0, b=np.inf, l=1.): r = -1 while not (a <= r < b): r = rand_expon(l) return r for b in np.linspace(5., 25., 5.): print "b=", b a=0. start = time.time() inv = [rand_expon_interval(a,b) for i in xrange(20000)] end = time.time() print "Time to generate numbers using inversion sampling: ", end-start start = time.time() inv = [rejection_sampler(expon, a=a, b=b, M=1.0001) for i in xrange(20000)] end = time.time() print "Time to generate numbers using rejection sampling: ", end-start print 7

8 Time to generate numbers using inversion sampling: Time to generate numbers using rejection sampling: b= 10.0 Time to generate numbers using inversion sampling: Time to generate numbers using rejection sampling: b= 15.0 Time to generate numbers using inversion sampling: Time to generate numbers using rejection sampling: b= 20.0 Time to generate numbers using inversion sampling: Time to generate numbers using rejection sampling: b= 25.0 Time to generate numbers using inversion sampling: Time to generate numbers using rejection sampling: We can see that this method is much faster than rejection sampling, because the exponential function drops off very fast Inversion sampling of discrete (measured) distributions In case we only have access to a discrete representation of a distribution, for example data measured by an instrument, we can also perform inversion sampling, though in a discrete fashion. The steps are basically the same as above, we just replace the analytical methods with numerical ones. Assume we have measured data which is distributed according to a distribution function F (x), in discrete bins x 0, x 1,... x n 1. Normalize F (x), N = N i=0 F (x i), then calculate the probability density function f(x) = F (x) N 2. Determine the CDF C(x) as cumulative sum of f(x): C(x) = x i=0 f(x i) 3. Sample a uniform random number u in [0, 1). 4. Sort u into C(x), and store the index t, i.e. calculate the histogram of all us. 5. The histogram generated in step 4 is distributed like F. Let s implement this now. We have already sampled values form the normal distribution, so we now histogram those values to generate an artifical measurement. In [9]: r = [np.random.randn(2000)] bins = np.linspace(-3,3,13) h, xb = np.histogram(r, bins=bins) x = xb[:-1] + 0.5*diff(xb) plot(x, h); 8

9 In [10]: f = 1.* h / h.sum() plot(x,f); 9

10 In [11]: c = f.cumsum() plot(x,c); 10

11 In [12]: u = np.random.random(2000) cbins = np.concatenate(([0],c)) h2, cb = np.histogram(u, bins=cbins) plot(x, h, label="measurement data"); plot(x, h2,label="random samples from measurement data"); ylim(0, h.max()*1.4) legend(); 11

12 500 Measurement data Random samples from measurement data In [ ]: 12

Visualisation in python (with Matplotlib)

Visualisation in python (with Matplotlib) Visualisation in python (with Matplotlib) Thanks to all contributors: Ag Stephens, Stephen Pascoe. Introducing Matplotlib Matplotlib is a python 2D plotting library which produces publication quality figures

More information

(DRAFT) PYTHON FUNDAMENTALS II: NUMPY & MATPLOTLIB

(DRAFT) PYTHON FUNDAMENTALS II: NUMPY & MATPLOTLIB (DRAFT) PYTHON FUNDAMENTALS II: NUMPY & MATPLOTLIB TROY P. KLING Contents 1. Importing Libraries 1 2. Introduction to numpy 2 3. Introduction to matplotlib 5 4. Image Processing 8 5. The Mandelbrot Set

More information

Probability Models.S4 Simulating Random Variables

Probability Models.S4 Simulating Random Variables Operations Research Models and Methods Paul A. Jensen and Jonathan F. Bard Probability Models.S4 Simulating Random Variables In the fashion of the last several sections, we will often create probability

More information

Tutorial 2 PHY409 Anadi Canepa Office, TRIUMF MOB 92 B ( )

Tutorial 2 PHY409 Anadi Canepa Office, TRIUMF MOB 92 B ( ) Tutorial 2 PHY409 Anadi Canepa canepa@triumf.ca Office, TRIUMF MOB 92 B (1-604- 222-7330) Alan Manning mannin2@phas.ubc.ca Mohammad Samani samani@physics.ubc.ca During the 1 st tutorial We learnt What

More information

Monte Carlo Integration and Random Numbers

Monte Carlo Integration and Random Numbers Monte Carlo Integration and Random Numbers Higher dimensional integration u Simpson rule with M evaluations in u one dimension the error is order M -4! u d dimensions the error is order M -4/d u In general

More information

Python in Economics and Finance

Python in Economics and Finance Python in Economics and Finance Part 2 John Stachurski, ANU June 2014 Topics Data types OOP Iteration Functions NumPy / SciPy Matplotlib Data Types We have already met several native Python data types»>

More information

Objectives. 1 Basic Calculations. 2 Matrix Algebra. Physical Sciences 12a Lab 0 Spring 2016

Objectives. 1 Basic Calculations. 2 Matrix Algebra. Physical Sciences 12a Lab 0 Spring 2016 Physical Sciences 12a Lab 0 Spring 2016 Objectives This lab is a tutorial designed to a very quick overview of some of the numerical skills that you ll need to get started in this class. It is meant to

More information

INTRODUCTORY NOTES ON MATLAB

INTRODUCTORY NOTES ON MATLAB INTRODUCTORY NOTES ON MATLAB C Lamas Fernández, S Marelli, B Sudret CHAIR OF RISK, SAFETY AND UNCERTAINTY QUANTIFICATION STEFANO-FRANSCINI-PLATZ 5 CH-8093 ZÜRICH Risk, Safety & Uncertainty Quantification

More information

Python for Scientists

Python for Scientists High level programming language with an emphasis on easy to read and easy to write code Includes an extensive standard library We use version 3 History: Exists since 1991 Python 3: December 2008 General

More information

Bi 1x Spring 2014: Plotting and linear regression

Bi 1x Spring 2014: Plotting and linear regression Bi 1x Spring 2014: Plotting and linear regression In this tutorial, we will learn some basics of how to plot experimental data. We will also learn how to perform linear regressions to get parameter estimates.

More information

Lecture 2: Introduction to Numerical Simulation

Lecture 2: Introduction to Numerical Simulation Lecture 2: Introduction to Numerical Simulation Ahmed Kebaier kebaier@math.univ-paris13.fr HEC, Paris Outline of The Talk 1 Simulation of Random variables Outline 1 Simulation of Random variables Random

More information

Objectives. 1 Running, and Interface Layout. 2 Toolboxes, Documentation and Tutorials. 3 Basic Calculations. PS 12a Laboratory 1 Spring 2014

Objectives. 1 Running, and Interface Layout. 2 Toolboxes, Documentation and Tutorials. 3 Basic Calculations. PS 12a Laboratory 1 Spring 2014 PS 12a Laboratory 1 Spring 2014 Objectives This session is a tutorial designed to a very quick overview of some of the numerical skills that you ll need to get started. Throughout the tutorial, the instructors

More information

% Close all figure windows % Start figure window

% Close all figure windows % Start figure window CS1112 Fall 2016 Project 3 Part A Due Monday 10/3 at 11pm You must work either on your own or with one partner. If you work with a partner, you must first register as a group in CMS and then submit your

More information

MO101: Python for Engineering Vladimir Paun ENSTA ParisTech

MO101: Python for Engineering Vladimir Paun ENSTA ParisTech I MO101: Python for Engineering Vladimir Paun ENSTA ParisTech License CC BY-NC-SA 2.0 http://creativecommons.org/licenses/by-nc-sa/2.0/fr/ Introduction to Python Introduction About Python Python itself

More information

What We ll Do... Random

What We ll Do... Random What We ll Do... Random- number generation Random Number Generation Generating random variates Nonstationary Poisson processes Variance reduction Sequential sampling Designing and executing simulation

More information

Parallel Computing with ipyparallel

Parallel Computing with ipyparallel Lab 1 Parallel Computing with ipyparallel Lab Objective: Most computers today have multiple processors or multiple processor cores which allow various processes to run simultaneously. To perform enormous

More information

PYTHON DATA VISUALIZATIONS

PYTHON DATA VISUALIZATIONS PYTHON DATA VISUALIZATIONS from Learning Python for Data Analysis and Visualization by Jose Portilla https://www.udemy.com/learning-python-for-data-analysis-and-visualization/ Notes by Michael Brothers

More information

CS302 Topics: * More on Simulation and Priority Queues * Random Number Generation

CS302 Topics: * More on Simulation and Priority Queues * Random Number Generation CS302 Topics: * More on Simulation and Priority Queues * Random Number Generation Thursday, Oct. 5, 2006 Greetings from Salvador, Brazil!! (i.e., from my recent trip to present a plenary lecture on multi-robot

More information

Numerical Calculations

Numerical Calculations Fundamentals of Programming (Python) Numerical Calculations Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Scipy Lecture Notes at http://www.scipy-lectures.org/ Outline

More information

Chapter 1. Introduction

Chapter 1. Introduction Chapter 1 Introduction A Monte Carlo method is a compuational method that uses random numbers to compute (estimate) some quantity of interest. Very often the quantity we want to compute is the mean of

More information

CME 193: Introduction to Scientific Python Lecture 5: Numpy, Scipy, Matplotlib

CME 193: Introduction to Scientific Python Lecture 5: Numpy, Scipy, Matplotlib CME 193: Introduction to Scientific Python Lecture 5: Numpy, Scipy, Matplotlib Sven Schmit stanford.edu/~schmit/cme193 5: Numpy, Scipy, Matplotlib 5-1 Contents Second part of course Numpy Scipy Matplotlib

More information

Python Crash Course Numpy, Scipy, Matplotlib

Python Crash Course Numpy, Scipy, Matplotlib Python Crash Course Numpy, Scipy, Matplotlib That is what learning is. You suddenly understand something you ve understood all your life, but in a new way. Doris Lessing Steffen Brinkmann Max-Planck-Institut

More information

#To import the whole library under a different name, so you can type "diff_name.f unc_name" import numpy as np import matplotlib.

#To import the whole library under a different name, so you can type diff_name.f unc_name import numpy as np import matplotlib. In [1]: #Here I import the relevant function libraries #This can be done in many ways #To import an entire library (e.g. scipy) so that functions accessed by typing "l ib_name.func_name" import matplotlib

More information

User-Defined Function

User-Defined Function ENGR 102-213 (Socolofsky) Week 11 Python scripts In the lecture this week, we are continuing to learn powerful things that can be done with userdefined functions. In several of the examples, we consider

More information

Physics 736. Experimental Methods in Nuclear-, Particle-, and Astrophysics. - Statistics and Error Analysis -

Physics 736. Experimental Methods in Nuclear-, Particle-, and Astrophysics. - Statistics and Error Analysis - Physics 736 Experimental Methods in Nuclear-, Particle-, and Astrophysics - Statistics and Error Analysis - Karsten Heeger heeger@wisc.edu Feldman&Cousin what are the issues they deal with? what processes

More information

MULTI-DIMENSIONAL MONTE CARLO INTEGRATION

MULTI-DIMENSIONAL MONTE CARLO INTEGRATION CS580: Computer Graphics KAIST School of Computing Chapter 3 MULTI-DIMENSIONAL MONTE CARLO INTEGRATION 2 1 Monte Carlo Integration This describes a simple technique for the numerical evaluation of integrals

More information

10.4 Linear interpolation method Newton s method

10.4 Linear interpolation method Newton s method 10.4 Linear interpolation method The next best thing one can do is the linear interpolation method, also known as the double false position method. This method works similarly to the bisection method by

More information

Use of Extreme Value Statistics in Modeling Biometric Systems

Use of Extreme Value Statistics in Modeling Biometric Systems Use of Extreme Value Statistics in Modeling Biometric Systems Similarity Scores Two types of matching: Genuine sample Imposter sample Matching scores Enrolled sample 0.95 0.32 Probability Density Decision

More information

10.1 Probability Distributions

10.1 Probability Distributions >> Lectures >> Matlab 10 Navigator 10.1 Probability Distributions This section discusses two basic probability density functions and probability distributions: uniform and normal, Gaussian mixture models,

More information

CME 193: Introduction to Scientific Python Lecture 6: Numpy, Scipy, Matplotlib

CME 193: Introduction to Scientific Python Lecture 6: Numpy, Scipy, Matplotlib CME 193: Introduction to Scientific Python Lecture 6: Numpy, Scipy, Matplotlib Nolan Skochdopole stanford.edu/class/cme193 6: Numpy, Scipy, Matplotlib 6-1 Contents Homeworks and Project Numpy Scipy Matplotlib

More information

Probability and Statistics for Final Year Engineering Students

Probability and Statistics for Final Year Engineering Students Probability and Statistics for Final Year Engineering Students By Yoni Nazarathy, Last Updated: April 11, 2011. Lecture 1: Introduction and Basic Terms Welcome to the course, time table, assessment, etc..

More information

LECTURE 22. Numerical and Scientific Computing Part 2

LECTURE 22. Numerical and Scientific Computing Part 2 LECTURE 22 Numerical and Scientific Computing Part 2 MATPLOTLIB We re going to continue our discussion of scientific computing with matplotlib. Matplotlib is an incredibly powerful (and beautiful!) 2-D

More information

Ch.5: Array computing and curve plotting (Part 1)

Ch.5: Array computing and curve plotting (Part 1) Ch.5: Array computing and curve plotting (Part 1) Joakim Sundnes 1,2 Hans Petter Langtangen 1,2 Simula Research Laboratory 1 University of Oslo, Dept. of Informatics 2 Sep 20, 2017 (Adjusted) Plan for

More information

Basic Beginners Introduction to plotting in Python

Basic Beginners Introduction to plotting in Python Basic Beginners Introduction to plotting in Python Sarah Blyth July 23, 2009 1 Introduction Welcome to a very short introduction on getting started with plotting in Python! I would highly recommend that

More information

Section 6.2: Generating Discrete Random Variates

Section 6.2: Generating Discrete Random Variates Section 6.2: Generating Discrete Random Variates Discrete-Event Simulation: A First Course c 2006 Pearson Ed., Inc. 0-13-142917-5 Discrete-Event Simulation: A First Course Section 6.2: Generating Discrete

More information

STATISTICAL THINKING IN PYTHON I. Introduction to Exploratory Data Analysis

STATISTICAL THINKING IN PYTHON I. Introduction to Exploratory Data Analysis STATISTICAL THINKING IN PYTHON I Introduction to Exploratory Data Analysis Exploratory data analysis The process of organizing, plotting, and summarizing a data set Exploratory data analysis can never

More information

MS6021 Scientific Computing. TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing

MS6021 Scientific Computing. TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing MS6021 Scientific Computing TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing Preliminary Notes on Python (v MatLab + other languages) When you enter Spyder (available on installing Anaconda),

More information

Manual_implementation_of_the_Mersenne_twister_PseudoRandom_N

Manual_implementation_of_the_Mersenne_twister_PseudoRandom_N Manual_implementation_of_the_Mersenne_twister_PseudoRandom_N May 4, 2017 1 Table of Contents 1 Manual implementation of the Mersenne twister PseudoRandom Number Generator (PRNG) 1.1 Common API for the

More information

Effective Programming Practices for Economists. 10. Some scientific tools for Python

Effective Programming Practices for Economists. 10. Some scientific tools for Python Effective Programming Practices for Economists 10. Some scientific tools for Python Hans-Martin von Gaudecker Department of Economics, Universität Bonn A NumPy primer The main NumPy object is the homogeneous

More information

Newton and Quasi-Newton Methods

Newton and Quasi-Newton Methods Lab 17 Newton and Quasi-Newton Methods Lab Objective: Newton s method is generally useful because of its fast convergence properties. However, Newton s method requires the explicit calculation of the second

More information

MATPLOTLIB. Python for computational science November 2012 CINECA.

MATPLOTLIB. Python for computational science November 2012 CINECA. MATPLOTLIB Python for computational science 19 21 November 2012 CINECA m.cestari@cineca.it Introduction (1) plotting the data gives us visual feedback in the working process Typical workflow: write a python

More information

Prob_and_RV_Demo. August 21, 2018

Prob_and_RV_Demo. August 21, 2018 Prob_and_RV_Demo August 21, 2018 Contents Probability and Random Variables 1 Bernoulli Trials........................................ 2 Histogram of the Random Variates......................... 3 Normal

More information

Lecture 15: High Dimensional Data Analysis, Numpy Overview

Lecture 15: High Dimensional Data Analysis, Numpy Overview Lecture 15: High Dimensional Data Analysis, Numpy Overview Chris Tralie, Duke University 3/3/2016 Announcements Mini Assignment 3 Out Tomorrow, due next Friday 3/11 11:55PM Rank Top 3 Final Project Choices

More information

Physics 736. Experimental Methods in Nuclear-, Particle-, and Astrophysics. - Statistical Methods -

Physics 736. Experimental Methods in Nuclear-, Particle-, and Astrophysics. - Statistical Methods - Physics 736 Experimental Methods in Nuclear-, Particle-, and Astrophysics - Statistical Methods - Karsten Heeger heeger@wisc.edu Course Schedule and Reading course website http://neutrino.physics.wisc.edu/teaching/phys736/

More information

Lab 1 - Basic ipython Tutorial (EE 126 Fall 2014)

Lab 1 - Basic ipython Tutorial (EE 126 Fall 2014) Lab 1 - Basic ipython Tutorial (EE 126 Fall 2014) modified from Berkeley Python Bootcamp 2013 https://github.com/profjsb/python-bootcamp and Python for Signal Processing http://link.springer.com/book/10.1007%2f978-3-319-01342-8

More information

(2) Hypothesis Testing

(2) Hypothesis Testing (2) Hypothesis Testing March 1, 2016 In [4]: %matplotlib inline #python includes import sys #standard probability includes: import numpy as np #matrices and data structures import scipy.stats as ss #standard

More information

Computational Physics Adaptive, Multi-Dimensional, & Monte Carlo Integration Feb 21, 2019

Computational Physics Adaptive, Multi-Dimensional, & Monte Carlo Integration Feb 21, 2019 Computational Physics Adaptive, Multi-Dimensional, & Monte Carlo Integration Feb 21, 219 http://hadron.physics.fsu.edu/~eugenio/comphy/ eugenio@fsu.edu f(x) trapezoidal rule Series Integration review from

More information

Partial Differential Equations II: 2D Laplace Equation on 5x5 grid

Partial Differential Equations II: 2D Laplace Equation on 5x5 grid Partial Differential Equations II: 2D Laplace Equation on 5x5 grid Sam Sinayoko Numerical Methods 5 Contents 1 Learning Outcomes 2 2 Introduction 3 3 Laplace equation in 2D 3 4 Discretisation 3 4.1 Meshing:

More information

CS 563 Advanced Topics in Computer Graphics Monte Carlo Integration: Basic Concepts. by Emmanuel Agu

CS 563 Advanced Topics in Computer Graphics Monte Carlo Integration: Basic Concepts. by Emmanuel Agu CS 563 Advanced Topics in Computer Graphics Monte Carlo Integration: Basic Concepts by Emmanuel Agu Introduction The integral equations generally don t have analytic solutions, so we must turn to numerical

More information

Modules and Clients 1 / 21

Modules and Clients 1 / 21 Modules and Clients 1 / 21 Outline 1 Using Functions in Other Programs 2 Modular Programming Abstractions 3 Random Numbers 4 List Processing 5 Standard Statistics 2 / 21 Using Functions in Other Programs

More information

Maine-Quebec Data Generation

Maine-Quebec Data Generation Maine-Quebec Data Generation October 4, 2016 1 Testing for a Generalized Conjecture on Sums of Coefficients of Cusp Forms Let f be a weight k cusp form with Fourier expansion f(z) = n 1 a(n)e(nz). Deligne

More information

lof April 23, Improving performance of Local outlier factor with KD-Trees

lof April 23, Improving performance of Local outlier factor with KD-Trees lof April 23, 2014 1 Improving performance of Local outlier factor with KD-Trees Local outlier factor (LOF) is an outlier detection algorithm, that detects outliers based on comparing local density of

More information

699DR git/github Tutorial

699DR git/github Tutorial 699DR git/github Tutorial Sep 20 2017 This tutorial gives a high-level introduction into basic usage of the version control software git in combination with the online platform Github. The git commands

More information

Monte Carlo Integration

Monte Carlo Integration Lab 18 Monte Carlo Integration Lab Objective: Implement Monte Carlo integration to estimate integrals. Use Monte Carlo Integration to calculate the integral of the joint normal distribution. Some multivariable

More information

COMPUTER SCIENCE LARGE PRACTICAL.

COMPUTER SCIENCE LARGE PRACTICAL. COMPUTER SCIENCE LARGE PRACTICAL Page 45 of 100 SURVEY RESULTS Approx. 1/5 of class responded; statistically significant? The majority of you have substantial experience in Java, and all have at least

More information

Plotting With matplotlib

Plotting With matplotlib Lab Plotting With matplotlib and Mayavi Lab Objective: Introduce some of the basic plotting functions available in matplotlib and Mayavi. -D plotting with matplotlib The Python library matplotlib will

More information

Computational Foundations of Cognitive Science. Inverse. Inverse. Inverse Determinant

Computational Foundations of Cognitive Science. Inverse. Inverse. Inverse Determinant Computational Foundations of Cognitive Science Lecture 14: s and in Matlab; Plotting and Graphics Frank Keller School of Informatics University of Edinburgh keller@inf.ed.ac.uk February 23, 21 1 2 3 Reading:

More information

Recursive Estimation

Recursive Estimation Recursive Estimation Raffaello D Andrea Spring 28 Problem Set : Probability Review Last updated: March 6, 28 Notes: Notation: Unless otherwise noted, x, y, and z denote random variables, p x denotes the

More information

Chapter 6: Simulation Using Spread-Sheets (Excel)

Chapter 6: Simulation Using Spread-Sheets (Excel) Chapter 6: Simulation Using Spread-Sheets (Excel) Refer to Reading Assignments 1 Simulation Using Spread-Sheets (Excel) OBJECTIVES To be able to Generate random numbers within a spreadsheet environment.

More information

Topic 6: Calculus Integration Volume of Revolution Paper 2

Topic 6: Calculus Integration Volume of Revolution Paper 2 Topic 6: Calculus Integration Standard Level 6.1 Volume of Revolution Paper 1. Let f(x) = x ln(4 x ), for < x

More information

Generating random samples from user-defined distributions

Generating random samples from user-defined distributions The Stata Journal (2011) 11, Number 2, pp. 299 304 Generating random samples from user-defined distributions Katarína Lukácsy Central European University Budapest, Hungary lukacsy katarina@phd.ceu.hu Abstract.

More information

Integration. Volume Estimation

Integration. Volume Estimation Monte Carlo Integration Lab Objective: Many important integrals cannot be evaluated symbolically because the integrand has no antiderivative. Traditional numerical integration techniques like Newton-Cotes

More information

Python Matplotlib. MACbioIDi February March 2018

Python Matplotlib. MACbioIDi February March 2018 Python Matplotlib MACbioIDi February March 2018 Introduction Matplotlib is a Python 2D plotting library Its origins was emulating the MATLAB graphics commands It makes heavy use of NumPy Objective: Create

More information

Will Monroe July 21, with materials by Mehran Sahami and Chris Piech. Joint Distributions

Will Monroe July 21, with materials by Mehran Sahami and Chris Piech. Joint Distributions Will Monroe July 1, 017 with materials by Mehran Sahami and Chris Piech Joint Distributions Review: Normal random variable An normal (= Gaussian) random variable is a good approximation to many other distributions.

More information

Mathematical Programming

Mathematical Programming Mathematical Programming Example #9-1. Minimize the following problem related to the linear programming. Minimize: f(x, y) = x + 4y Subject to: 3x + y 6 x + 2y 4 y 3 where x TA: Junhee Lee Python Code

More information

Homework: Study 6.1 # 1, 5, 7, 13, 25, 19; 3, 17, 27, 53

Homework: Study 6.1 # 1, 5, 7, 13, 25, 19; 3, 17, 27, 53 January, 7 Goals:. Remember that the area under a curve is the sum of the areas of an infinite number of rectangles. Understand the approach to finding the area between curves.. Be able to identify the

More information

Derek Bridge School of Computer Science and Information Technology University College Cork

Derek Bridge School of Computer Science and Information Technology University College Cork CS4618: rtificial Intelligence I Vectors and Matrices Derek Bridge School of Computer Science and Information Technology University College Cork Initialization In [1]: %load_ext autoreload %autoreload

More information

EECS 126 Probability and Random Processes University of California, Berkeley: Fall 2017 Abhay Parekh and Jean Walrand September 21, 2017.

EECS 126 Probability and Random Processes University of California, Berkeley: Fall 2017 Abhay Parekh and Jean Walrand September 21, 2017. EECS 126 Probability and Random Processes University of California, Berkeley: Fall 2017 Abhay Parekh and Jean Walrand September 21, 2017 Midterm Exam Last Name First Name SID Rules. You have 80 minutes

More information

Today s outline: pp

Today s outline: pp Chapter 3 sections We will SKIP a number of sections Random variables and discrete distributions Continuous distributions The cumulative distribution function Bivariate distributions Marginal distributions

More information

An Introduction to PDF Estimation and Clustering

An Introduction to PDF Estimation and Clustering Sigmedia, Electronic Engineering Dept., Trinity College, Dublin. 1 An Introduction to PDF Estimation and Clustering David Corrigan corrigad@tcd.ie Electrical and Electronic Engineering Dept., University

More information

CDA6530: Performance Models of Computers and Networks. Chapter 8: Statistical Simulation --- Discrete-Time Simulation

CDA6530: Performance Models of Computers and Networks. Chapter 8: Statistical Simulation --- Discrete-Time Simulation CDA6530: Performance Models of Computers and Networks Chapter 8: Statistical Simulation --- Discrete-Time Simulation Simulation Studies Models with analytical formulas Calculate the numerical solutions

More information

Problems from Hughes and Hase

Problems from Hughes and Hase Problems from Hughes and Hase In [1]: import scipy as sp from scipy import stats import matplotlib as mpl # As of July 017 Bucknell computers use v..x import matplotlib.pyplot as plt # Following is an

More information

14.30 Introduction to Statistical Methods in Economics Spring 2009

14.30 Introduction to Statistical Methods in Economics Spring 2009 MIT OpenCourseWare http://ocw.mit.edu 14.30 Introduction to Statistical Methods in Economics Spring 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

More information

Outline. 1 Using Functions in Other Programs. 2 Modular Programming Abstractions. 3 Random Numbers. 4 List Processing. 5 Standard Statistics 1 / 21

Outline. 1 Using Functions in Other Programs. 2 Modular Programming Abstractions. 3 Random Numbers. 4 List Processing. 5 Standard Statistics 1 / 21 Outline 1 Using Functions in Other Programs Modules and Clients 2 Modular Programming Abstractions 3 Random Numbers 4 5 Standard Statistics 1 / 21 2 / 21 Using Functions in Other Programs Modular Programming

More information

Homework 11 - Debugging

Homework 11 - Debugging 1 of 7 5/28/2018, 1:21 PM Homework 11 - Debugging Instructions: Fix the errors in the following problems. Some of the problems are with the code syntax, causing an error message. Other errors are logical

More information

Stat 302 Statistical Software and Its Applications SAS: Distributions

Stat 302 Statistical Software and Its Applications SAS: Distributions Stat 302 Statistical Software and Its Applications SAS: Distributions Yen-Chi Chen Department of Statistics, University of Washington Autumn 2016 1 / 39 Distributions in R and SAS Distribution R SAS Beta

More information

Package simed. November 27, 2017

Package simed. November 27, 2017 Version 1.0.3 Title Simulation Education Author Barry Lawson, Larry Leemis Package simed November 27, 2017 Maintainer Barry Lawson Imports graphics, grdevices, methods, stats, utils

More information

Physics 736. Experimental Methods in Nuclear-, Particle-, and Astrophysics. Lecture 14

Physics 736. Experimental Methods in Nuclear-, Particle-, and Astrophysics. Lecture 14 Physics 736 Experimental Methods in Nuclear-, Particle-, and Astrophysics Lecture 14 Karsten Heeger heeger@wisc.edu Course Schedule and Reading course website http://neutrino.physics.wisc.edu/teaching/phys736/

More information

Using the Matplotlib Library in Python 3

Using the Matplotlib Library in Python 3 Using the Matplotlib Library in Python 3 Matplotlib is a Python 2D plotting library that produces publication-quality figures in a variety of hardcopy formats and interactive environments across platforms.

More information

Statistics for HEP Hands-on Tutorial #2. Nicolas Berger (LAPP)

Statistics for HEP Hands-on Tutorial #2. Nicolas Berger (LAPP) Statistics for HEP Hands-on Tutorial #2 Nicolas Berger (LAPP) Introduction We will use the same setup as the previous tutorial to compute significances and upper limits Two main examples Gaussian S+B measurement

More information

An Excel Add-In for Capturing Simulation Statistics

An Excel Add-In for Capturing Simulation Statistics 2001 Joint Statistical Meetings Atlanta, GA An Excel Add-In for Capturing Simulation Statistics David C. Trindade david.trindade@sun.com Sun Microsystems, Inc. Cupertino, CA David Meade david.meade@amd.com

More information

CS302 Topic: Simulation, Part II

CS302 Topic: Simulation, Part II CS302 Topic: Simulation, Part II Thursday, Oct. 6, 200 Gone out Here is a computer simulation of your dinner Announcements Lab 4 (Stock Reports); due this Friday, Oct. Lab (Algorithm Analysis) now available;

More information

CS 237 Fall 2018, Homework 08 Solution

CS 237 Fall 2018, Homework 08 Solution CS 237 Fall 2018, Homework 08 Solution Due date: Thursday November 8th at 11:59 pm (10% off if up to 24 hours late) via Gradescope General Instructions Please complete this notebook by filling in solutions

More information

Slides from INF3331 lectures optimizing Python code

Slides from INF3331 lectures optimizing Python code Slides from INF3331 lectures optimizing Python code p. 1/20 Slides from INF3331 lectures optimizing Python code Ola Skavhaug, Joakim Sundnes and Hans Petter Langtangen Dept. of Informatics, Univ. of Oslo

More information

Introduction to Python: The Multi-Purpose Programming Language. Robert M. Porsch June 14, 2017

Introduction to Python: The Multi-Purpose Programming Language. Robert M. Porsch June 14, 2017 Introduction to Python: The Multi-Purpose Programming Language Robert M. Porsch June 14, 2017 What is Python Python is Python is a widely used high-level programming language for general-purpose programming

More information

ELEN E4830 Digital Image Processing. Homework 3 Solution

ELEN E4830 Digital Image Processing. Homework 3 Solution ELEN E48 Digital Image Processing Homework Solution Chuxiang Li cxli@ee.columbia.edu Department of Electrical Engineering, Columbia University February 4, 6 Image Histogram Stretching. Histogram of Gray-image

More information

Part VI. Scientific Computing in Python. Alfredo Parra : Scripting with Python Compact Max-PlanckMarch 6-10,

Part VI. Scientific Computing in Python. Alfredo Parra : Scripting with Python Compact Max-PlanckMarch 6-10, Part VI Scientific Computing in Python Compact Course @ Max-PlanckMarch 6-10, 2017 63 Doing maths in Python Standard sequence types (list, tuple,... ) Can be used as arrays Can contain different types

More information

Laplace Transform of a Lognormal Random Variable

Laplace Transform of a Lognormal Random Variable Approximations of the Laplace Transform of a Lognormal Random Variable Joint work with Søren Asmussen & Jens Ledet Jensen The University of Queensland School of Mathematics and Physics August 1, 2011 Conference

More information

Computational Methods. Randomness and Monte Carlo Methods

Computational Methods. Randomness and Monte Carlo Methods Computational Methods Randomness and Monte Carlo Methods Manfred Huber 2010 1 Randomness and Monte Carlo Methods Introducing randomness in an algorithm can lead to improved efficiencies Random sampling

More information

Lab 5 Monte Carlo integration

Lab 5 Monte Carlo integration Lab 5 Monte Carlo integration Edvin Listo Zec 9065-976 edvinli@student.chalmers.se October 0, 014 Co-worker: Jessica Fredby Introduction In this computer assignment we will discuss a technique for solving

More information

Applied Calculus. Lab 1: An Introduction to R

Applied Calculus. Lab 1: An Introduction to R 1 Math 131/135/194, Fall 2004 Applied Calculus Profs. Kaplan & Flath Macalester College Lab 1: An Introduction to R Goal of this lab To begin to see how to use R. What is R? R is a computer package for

More information

Lecture #5. Point transformations (cont.) Histogram transformations. Intro to neighborhoods and spatial filtering

Lecture #5. Point transformations (cont.) Histogram transformations. Intro to neighborhoods and spatial filtering Lecture #5 Point transformations (cont.) Histogram transformations Equalization Specification Local vs. global operations Intro to neighborhoods and spatial filtering Brightness & Contrast 2002 R. C. Gonzalez

More information

VARIANCE REDUCTION TECHNIQUES IN MONTE CARLO SIMULATIONS K. Ming Leung

VARIANCE REDUCTION TECHNIQUES IN MONTE CARLO SIMULATIONS K. Ming Leung POLYTECHNIC UNIVERSITY Department of Computer and Information Science VARIANCE REDUCTION TECHNIQUES IN MONTE CARLO SIMULATIONS K. Ming Leung Abstract: Techniques for reducing the variance in Monte Carlo

More information

LECTURE 19. Numerical and Scientific Packages

LECTURE 19. Numerical and Scientific Packages LECTURE 19 Numerical and Scientific Packages NUMERICAL AND SCIENTIFIC APPLICATIONS As you might expect, there are a number of third-party packages available for numerical and scientific computing that

More information

ORGANIZING THE DATA IN A FREQUENCY TABLE

ORGANIZING THE DATA IN A FREQUENCY TABLE ORGANIZING THE DATA IN A FREQUENCY TABLE Suppose the scores obtained by 5 students on a standardized test are as follows: 68, 55, 61, 55, 43, 59, 55, 58, 77, 6, 56, 53, 58, 7, 57, 62, 5, 69, 44, 63, 48,79,

More information

Course May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points

Course May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points May 18, 2017 3 I/O 3 I/O 3 I/O 3 ASC, room A 238, phone 089-21804210, email hartmut.ruhl@lmu.de Patrick Böhl, ASC, room A205, phone 089-21804640, email patrick.boehl@physik.uni-muenchen.de. I/O Scientific

More information

Matplotlib Python Plotting

Matplotlib Python Plotting Matplotlib Python Plotting 1 / 6 2 / 6 3 / 6 Matplotlib Python Plotting Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive

More information

epub WU Institutional Repository

epub WU Institutional Repository epub WU Institutional Repository Josef Leydold and Wolfgang Hörmann The Automatic Generation of One- and Multi-dimensional Distributions with Transformed Density Rejection Paper Original Citation: Leydold,

More information

Page 129 Exercise 5: Suppose that the joint p.d.f. of two random variables X and Y is as follows: { c(x. 0 otherwise. ( 1 = c. = c

Page 129 Exercise 5: Suppose that the joint p.d.f. of two random variables X and Y is as follows: { c(x. 0 otherwise. ( 1 = c. = c Stat Solutions for Homework Set Page 9 Exercise : Suppose that the joint p.d.f. of two random variables X and Y is as follows: { cx fx, y + y for y x, < x < otherwise. Determine a the value of the constant

More information

Topic 5 - Joint distributions and the CLT

Topic 5 - Joint distributions and the CLT Topic 5 - Joint distributions and the CLT Joint distributions Calculation of probabilities, mean and variance Expectations of functions based on joint distributions Central Limit Theorem Sampling distributions

More information