• API
• FAQ
• Tools
• Archive
SHARE
TWEET # Untitled a guest Nov 9th, 2018 76 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. """
2. A distribution is considered to be a dictionary that maps every value to its corresponding probability, also this
3. module works only for distributions that take finite number of values.
4. """
5. import numpy as np
6.
7. from collections import defaultdict
8. from itertools import product
9. from pprint import pprint
10.
11.
12. def mean(dist):
13.     """
14.    Returns the mean of the given distribution
15.    """
16.     return np.sum([i * dist[i] for i in dist])
17.
18.
19. def cdf(dist, val):
20.     """
21.    Computes the CDF for the given distribution and value. i.e P(dist < val)
22.    """
23.     return np.sum([dist[i] for i in dist if i <= val])
24.
25.
26. def nfoldconv(dist, n):
27.     """
28.    Returns a distribution that is the sum of `n` independent random variables `dist`. Note that because of python's bad
29.    floating point precision, numpy is used to calculate the probabilities (full accuracy is still not guaranteed).
30.
31.    :return: A distribution in the format that is described in the module docs.
32.    """
33.     new_dist = defaultdict(int)  # int defaults to 0
34.     for combination in product(dist, repeat=n):
35.         new_dist[sum(combination)] += np.prod(map(lambda val: np.float64(dist[val]), combination))
36.
37.     print sum(new_dist.values())
38.     return dict(new_dist)
39.
40.
41. if __name__ == '__main__':
42.     # b
43.     fair_dice = {i: 1.0 / 6 for i in range(1, 7)}
44.     fair_dice_sum = nfoldconv(fair_dice, 6)
45.     print '\nB:'
46.     pprint(fair_dice_sum)
47.     pprint(mean(fair_dice_sum))
48.
49.     # c
50.     price_stock_change = {-1: 0.1, 0: 0.25, 1: 0.35, 2: 0.05, 3: 0.25}
51.     print '\nC:'
52.     pprint(nfoldconv(price_stock_change, 2))
53.     pprint(nfoldconv(price_stock_change, 5))
54.
55.     # d
56.     stock_after_five_days = nfoldconv(price_stock_change, 5)
57.     print '\nD:'
58.     print 1 - cdf(stock_after_five_days, 7)  # CDF computes the probability that we gained less than 7 NIS
59.     print cdf(stock_after_five_days, -7)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top