Thread: Math Quiz 9
View Single Post
  #88   Spotlight this post!  
Unread 08-08-2016, 23:32
Greg Woelki's Avatar
Greg Woelki Greg Woelki is offline
FRC Alumnus
FRC #1768
 
Join Date: May 2014
Rookie Year: 2013
Location: Bolton, MA
Posts: 97
Greg Woelki is a glorious beacon of lightGreg Woelki is a glorious beacon of lightGreg Woelki is a glorious beacon of lightGreg Woelki is a glorious beacon of lightGreg Woelki is a glorious beacon of light
Re: Math Quiz 9

Quote:
Originally Posted by Ether View Post
1) How long did 4e10 trials take to run?
About 16 hours. My laptop has an Intel Core i7-6700HQ Quad Core and I ran 4 copies of my program at once instead of implementing multithreading. This seemed to work as desired based on the cpu usage and left me with enough overhead to not impact my normal computer use.

Quote:
Originally Posted by Ether View Post
2) Yes, please post your code.
Internal points code:

Code:
import numpy as np
import time

def genPt(r_cir):
    
    r = r_cir*(np.random.random()**0.5) #Square root correction ensures even probability distribution over area
    theta = 2*np.pi*np.random.random()
    
    x = r*np.cos(theta)
    y = r*np.sin(theta)
    
    return x,y


t = time.time()

trials = 10**9

r = 1.0

total = 0.0

for i in range(trials):
    x1,y1 = genPt(r)
    x2,y2 = genPt(r)

    total += ((x2-x1)**2 + (y2-y1)**2)**0.5
    
    if not i%10**7:
        print(i)
        print(total/(i+1))
        print('')

    
print(total/trials)
print(time.time()-t)
Chord problem code:

Code:
import numpy as np
import time

t = time.time()

trials = 10**10 #Number of random samples

total = 0.0

r = 1.0

x1,y1 = 0.0,r

for i in range(trials):
    
    theta = 2*np.pi*np.random.random()
    
    x2 = r*np.cos(theta)
    y2 = r*np.sin(theta)

    total += ((x2-x1)**2 + (y2-y1)**2)**0.5
    
    if not i%10**7:
        print(i)
        print(total/(i+1))
        print('')

    
print(total/trials)
print(time.time()-t)
I have since made both programs about 2.5x faster by using the polar distance formula to cut down on trig functions (really add up after a few billion trials), by cutting the number of angles generated from 2 to 1 in each trial of the line segment problem, and by switching to using the math module trig functions instead of the NumPy ones. I was somewhat surprised to find that the math module ones are about twice as fast as NumPy's. I've often been impressed by the speed of doing things in NumPy, but it turns out that the Python developers also have some idea what they're doing .

Quote:
Originally Posted by Ether View Post
3) What's the period of the PRNG you used?
I used numpy.random.random(), which uses the Mersenne Twister sequence and has a period of 2^19937 − 1. Unfortunately I wasn't able to run quite that many trials.
Reply With Quote