# Python Course homework 3

Consider the polynomial expression

$$p(x) = a_0 + a_1 x + a_2 x^2 + \cdots a_N x^N = \sum_{n=0}^N a_n x^n$$

Earlier, you wrote a simple function p(x, coeff) to evaluate (1) without considering efficiency

Now write a new function that does the same job, but uses NumPy arrays and array operations for its computations, rather than any form of Python loop

(Such functionality is already implemented as np.poly1d, but for the sake of the exercise don’t use this class)

Hint: Use np.cumprod()

# -*- coding: utf-8 -*-
"""
Created on Sun Nov 25 21:00:33 2018

@author: Wengsway

"""

import numpy as np

N = int(input("请输入一个正整数作为 N："))
X = int(input("请输入一个值作为X："))
X_ARRAY = np.full(N, X, dtype=int)
X_ARRAY = np.insert(X_ARRAY, 0, 1)
A = input("请以空格为间隔连续输入一个数组:")
A_ARRAY = np.array(list(map(int, A.strip().split())))
B = np.array([A_ARRAY, np.cumprod(X_ARRAY)])
C = np.cumprod(B, axis=0)
print("\n", "最终的结果为：", sum(C))

Let q be a NumPy array of length n with q.sum() == 1

Suppose that q represents a probability mass function

We wish to generate a discrete random variable $x$ such that $\mathbb P\{x = i\} = q_i$

In other words, x takes values in range(len(q)) and x = i with probability q[i]

The standard (inverse transform) algorithm is as follows:

• Divide the unit interval $[0, 1]$ into $n$ subintervals $I_0, I_1, \ldots, I_{n-1}$ such that the length of $I_i$ is $q_i$
• Draw a uniform random variable $U$ on $[0, 1]$ and return the $i$ such that $U \in I_i$

The probability of drawing $i$ is the length of $I_i$, which is equal to $q_i$

We can implement the algorithm as follows

from random import uniform

def sample(q):
a = 0.0
U = uniform(0, 1)
for i in range(len(q)):