def plot_retention(lmbda, a, t0, t1): assert isinstance(lmbda, const) assert isinstance(a, const) assert isinstance(t0, const) assert isinstance(t1, const) rt = percent_retention_model(lmbda, a) rt_fn = tof(rt) derv_rt = deriv(rt) derv_tof = tof(derv_rt) xvals = np.linspace(t0.get_val(), t1.get_val(), 10000) yvals1 = np.array([rt_fn(x) for x in xvals]) xvals2 = np.linspace(t0.get_val(), t1.get_val(), 10000) yvals2 = np.array([derv_tof(x) for x in xvals]) fig1 = plt.figure(1) fig1.suptitle('Ebbinghaus Model of Forgetting') plt.xlabel('t') plt.ylabel('prf and dprf') plt.ylim([-20, 100]) plt.xlim([t0.get_val(), t1.get_val()]) plt.grid() plt.plot(xvals, yvals1, label='prf', c='r') plt.plot(xvals2, yvals2, label='dprf', c='b') plt.legend(loc='best') plt.show()
def plot_spread_of_news(p, k, tl, tu): assert isinstance(p, const) and isinstance(k, const) assert isinstance(tl, const) and isinstance(tu, const) nm = spread_of_news_model(p, k) nm_tof = tof(nm) deriv_nm = deriv(nm) deriv_nm_tof = tof(deriv_nm) xvals = np.linspace(tl.get_val(), tu.get_val(), 10000) yvals1 = np.array([nm_tof(x) for x in xvals]) xvals2 = np.linspace(tl.get_val(), tu.get_val(), 10000) yvals2 = np.array([deriv_nm_tof(x) for x in xvals]) fig1 = plt.figure(1) fig1.suptitle('Spread of News') plt.xlabel('t') plt.ylabel('snf and dsnf') plt.ylim([-2000, 52000]) plt.xlim([tl.get_val(), tu.get_val()]) plt.grid() plt.plot(xvals, yvals1, label='snf', c='r') plt.plot(xvals2, yvals2, label='dsnf', c='b') plt.legend(loc='best') plt.show()
def plot_plant_growth(m, t0, h0, t1, h1, tl, tu): assert isinstance(m, const) and isinstance(t1, const) assert isinstance(t0, const) and isinstance(h0, const) assert isinstance(h1, const) and isinstance(tl, const) assert isinstance(tu, const) pg = plant_growth_model(m, t0, h0, t1, h1) pg_tof = tof(pg) derv_pg = deriv(pg) derv_tof = tof(derv_pg) xvals = np.linspace(tl.get_val() - t0.get_val(), tu.get_val(), 10000) yvals1 = np.array([pg_tof(x) for x in xvals]) xvals2 = np.linspace(tl.get_val() - t0.get_val(), tu.get_val(), 10000) yvals2 = np.array([derv_tof(x) for x in xvals2]) fig1 = plt.figure(1) fig1.suptitle('Plant Growth') plt.xlabel('t') plt.ylabel('pgf and dpgf') plt.ylim([-2, 58]) plt.xlim([tl.get_val() - t0.get_val(), tu.get_val()]) plt.grid() plt.plot(xvals, yvals1, label='pgf', c='r') plt.plot(xvals2, yvals2, label='dpgf', c='b') plt.legend(loc='best') plt.show()
def test_10(self): #(3x+2)^4 print("****Unit Test 10********") fex0 = make_prod(make_const(3.0), make_pwr('x', 1.0)) fex1 = make_plus(fex0, make_const(2.0)) fex = make_pwr_expr(fex1, 4.0) print(fex) afex = antideriv(fex) assert not afex is None print(afex) afexf = tof(afex) err = 0.0001 def gt(x): return (1.0 / 15) * ((3 * x + 2.0)**5) for i in range(1, 10): assert abs(afexf(i) - gt(i)) <= err fexf = tof(fex) assert not fexf is None fex2 = deriv(afex) assert not fex2 is None print(fex2) fex2f = tof(fex2) assert not fex2f is None for i in range(1, 1000): assert abs(fexf(i) - fex2f(i)) <= err print('Test 10:pass')
def plot_spread_of_disease(p, t0, p0, t1, p1, tl, tu): assert isinstance(p, const) and isinstance(t0, const) assert isinstance(p0, const) and isinstance(t1, const) rt = spread_of_disease_model(p, t0, p0, t1, p1) rt_tof = tof(rt) derv_rt = deriv(rt) derv_tof = tof(derv_rt) xvals = np.linspace(tl.get_val(), tu.get_val(), 10000) yvals1 = np.array([rt_tof(x) for x in xvals]) xvals2 = np.linspace(tl.get_val(), tu.get_val(), 10000) yvals2 = np.array([derv_tof(x) for x in xvals]) fig1 = plt.figure(1) fig1.suptitle('Spread of Disease') plt.xlabel('t') plt.ylabel('sdf and dsdf') plt.ylim([0, 100000]) plt.xlim([tl.get_val(), tu.get_val()]) plt.grid() plt.plot(xvals, yvals1, label='sdf', c='r') plt.plot(xvals2, yvals2, label='dsdf', c='b') plt.legend(loc='best') plt.show()
def plot_spread_of_disease(p, t0, p0, t1, p1, tl, tu): assert isinstance(p, const) and isinstance(t0, const) assert isinstance(p0, const) and isinstance(t1, const) expr = spread_of_disease_model(p, t0, p0, t1, p1) disease = tof(expr) disease_derive = tof(deriv(expr)) min = tl.get_val() max = tu.get_val() xvals = np.linspace(min, max, 10000) yvals1 = np.array([disease(x) for x in xvals]) yvals2 = np.array([disease_derive(x) for x in xvals]) fig1 = plt.figure(1) fig1.suptitle("Spread of Disease") plt.xlabel('t') plt.ylabel('sdf and dsdf') ymax = max(np.max(yvals1), np.max(yvals2)) ymin = min(np.min(yvals1), np.min(yvals2)) plt.ylim([ymin, ymax]) plt.xlim([min, max]) plt.grid() plt.plot(xvals, yvals1, label='sdf', c='r') plt.plot(xvals, yvals2, label='dsdf', c='b') plt.legend(loc='best') plt.show()
def test_08(self): #(5x-7)^-2 => -1/5 * (5x-7)^-1 print("****Unit Test 08********") fex1 = make_plus(make_prod(make_const(5.0), make_pwr('x', 1.0)), make_const(-7.0)) fex = make_pwr_expr(fex1, -2.0) print(fex) afex = antideriv(fex) assert not afex is None print("antideriv: ", afex) afexf = tof(afex) err = 0.0001 def gt(x): return (-1.0 / 5.0) * ((5 * x - 7.0)**-1) for i in range(1, 100): assert abs(afexf(i) - gt(i)) <= err fexf = tof(fex) assert not fexf is None fex2 = deriv(afex) assert not fex2 is None print("deriv fex2: ", fex2) fex2f = tof(fex2) assert not fex2f is None for i in range(1, 100): print(fexf(i), " ", fex2f(i)) assert abs(fexf(i) - fex2f(i)) <= err print('Test 08:pass')
def plot_spread_of_news(p, k, tl, tu): assert isinstance(p, const) and isinstance(k, const) assert isinstance(tl, const) and isinstance(tu, const) expr = spread_of_news_model(p, k) news = tof(expr) expr_deriv = deriv(expr) news_deriv = tof(expr_deriv) min = tl.get_val() max = tu.get_val() xvals = np.linspace(min, max, 10000) yvals1 = np.array([news(x) for x in xvals]) yvals2 = np.array([news_deriv(x) for x in xvals]) fig1 = plt.figure(1) fig1.suptitle("Spread of News") plt.xlabel('t') plt.ylabel('snf and dsnf') ymax = max(np.max(yvals1), np.max(yvals2)) ymin = min(np.min(yvals1), np.min(yvals2)) plt.ylim([ymin, ymax]) plt.xlim([min, max]) plt.grid() plt.plot(xvals, yvals1, label='snf', c='r') plt.plot(xvals, yvals2, label='dnsf', c='b') plt.legend(loc='best') plt.show() if __name__ == '__main__': print("test 1: ") fex = percent_retention_model(make_const(1.0), make_const(1.0))
def gt21_02(x): ''' ground truth for 2nd taylor of fexpr2_01. ''' fexpr2_01 = make_prod(make_pwr('x', 1.0), make_e_expr(make_pwr('x', 1.0))) f0 = tof(fexpr2_01) f1 = tof(deriv(fexpr2_01)) f2 = tof(deriv(deriv(fexpr2_01))) return f0(2.0) + f1(2.0) * (x - 2.0) + (f2(2.0) / 2) * (x - 2.0)**2
def test_09(self): #3*(x+2)^-1 => 3*ln|x+2| print("****Unit Test 09********") fex0 = make_plus(make_pwr('x', 1.0), make_const(2.0)) fex1 = make_pwr_expr(fex0, -1.0) fex = make_prod(make_const(3.0), fex1) print(fex) afex = antideriv(fex) print("antideriv: ", afex) err = 0.0001 afexf = tof(afex) def gt(x): return 3.0 * math.log(abs(2.0 + x), math.e) for i in range(1, 101): assert abs(afexf(i) - gt(i)) <= err assert not afex is None print(afex) fexf = tof(fex) assert not fexf is None fex2 = deriv(afex) assert not fex2 is None print(fex2) fex2f = tof(fex2) assert not fex2f is None for i in range(1, 1000): assert abs(fexf(i) - fex2f(i)) <= err print('Test 09:pass')
def maximize_revenue( dmnd_eq, constraint=lambda x: x >= 0): #only works on linear demand eqs rev = incrementPolyPwrs(dmnd_eq, 1) rev_drv = deriv(rev) # print 'eq:',dmnd_eq # print 'rev',rev # print 'rev deriv',rev_drv rev_drv_f = tof(rev_drv) dmnd_f = tof(dmnd_eq) rev_f = tof(rev) # print 'f(20)',dmnd_f(20) # print 'R(20)',rev_f(20) # print 'R`(20)',rev_drv_f(20) xtrm = loc_xtrm_2nd_drv_test(rev) for val in xtrm: # print val[0] # print val[1] x = val[1].get_x().get_val() y = val[1].get_y().get_val() if (val[0] == 'max' and constraint(x)): num_units = const(x) revenue = const(y) price = const(dmnd_f(x)) return (num_units, revenue, price)
def plot_plant_growth(m, t1, x1, t2, x2, tl, tu): assert isinstance(m, const) and isinstance(t1, const) assert isinstance(x1, const) and isinstance(t2, const) assert isinstance(x2, const) and isinstance(tl, const) assert isinstance(tu, const) expr = plant_growth_model(m, t1, x1, t2, x2) growth = tof(expr) growth_deriv = tof(deriv(expr)) min = tl.get_val() max = tu.get_val() xvals = np.linspace(min, max, 10000) yvals1 = np.array([growth(x) for x in xvals]) yvals2 = np.array([growth_deriv(x) for x in xvals]) fig1 = plt.figure(1) fig1.suptitle("Plant Growth") plt.xlabel('t') plt.ylabel('pgf and dgdf') ymax = max(np.max(yvals1), np.max(yvals2)) ymin = min(np.min(yvals1), np.min(yvals2)) plt.ylim([ymin, ymax]) plt.xlim([min, max]) plt.grid() plt.plot(xvals, yvals1, label='pgf', c='r') plt.plot(xvals, yvals2, label='dgdf', c='b') plt.legend(loc='best') plt.show()
def consumer_surplus(dexpr, a): assert isinstance(a, const) B = const(-1 * tof(dexpr)(a.get_val())) f = make_plus(dexpr, B) surplus = tof(antideriv(f)) return surplus(a.get_val()) - surplus(0)
def evaluate_expression(expr, abc): # ((((1/3)*3(x^(3-1)) +-(2)*(x^(2-1)) + (3)*(x^(1-1)) + 0) if abc['a'] != None and abc['b'] != None and abc['c'] != None: return abc if isinstance(expr, plus): # a + b^1 results = evaluate_expression(expr.get_elt1(), abc) if results['degrees'] == 2: results['a'] = 1 results['degrees'] = -1 elif results['degrees'] == 1: results['b'] = 1 results['degrees'] = -1 elif results['degrees'] == 0: results['c'] = 1 results['degrees'] = -1 results = evaluate_expression(expr.get_elt2(), abc) # should be 5 if results['degrees'] == 2: results['a'] = 2 results['degrees'] = -1 elif results['degrees'] == 1: results['b'] = 1 results['degrees'] = -1 elif results['degrees'] == 0: results['c'] = 1 results['degrees'] = -1 if isinstance(expr.get_elt2(), const): results['c'] = expr.get_elt2().get_val() return results elif isinstance(expr, prod): # 3 * x^1 evaluate_expression(expr.get_mult1(), abc) results = evaluate_expression(expr.get_mult2(), abc) if results['degrees'] == 2: results['a'] = tof(expr.get_mult1())(0) results['degrees'] = -1 elif results['degrees'] == 1: results['b'] = tof(expr.get_mult1())(0) results['degrees'] = -1 elif results['degrees'] == 0: results['c'] = tof(expr.get_mult1())(0) results['degrees'] = -1 return results elif isinstance(expr, pwr): # x^1 if isinstance(expr.get_base(), var): abc['degrees'] = tof(expr.get_deg())(0) # should be a 1 return abc else: evaluate_expression(pwr.get_base(), abc) return abc
def newton_raphson(poly_fexpr, g, n): tof_expr = tof(poly_fexpr) deriv_expr = tof(deriv(poly_fexpr)) for i in range(n.get_val()): x = g.get_val() - (tof_expr(g.get_val()) / deriv_expr(g.get_val())) g = const(x) return g
def demand_elasticity(demand_eq, price): assert isinstance(price, const) # E(p) = (-p*f`(p))/f(p) f = tof(demand_eq) drv = deriv(demand_eq) fprime = tof(drv) p = price.get_val() return const((-p * fprime(p)) / f(p))
def demand_elasticity(demand_eq, price): assert isinstance(price, const) fx_drv = tof(deriv(demand_eq)) fx = tof(demand_eq) p = price.get_val() n = (-1.0 * p) * fx_drv(p) d = fx(p) return n / d
def line_intersection(lneq1, lneq2): # Case 1: 2 const lines if is_const_line(lneq1): if is_const_line(lneq2): if lneq1.get_lhs().get_name() == 'x': x = lneq1.get_rhs().get_val() y = lneq2.get_rhs().get_val() elif lneq1.get_lhs().get_name() == 'y': y = lneq1.get_rhs().get_val() x = lneq2.get_rhs().get_val() else: raise Exception('line_intersection: ' + str(lneq1)) else: y = lneq1.get_rhs().get_val() x = tof(lneq2.get_rhs())(y) elif is_const_line(lneq2): #Case 2: 1 const line y = 1 ;y = x -1 y = lneq2.get_rhs().get_val() x = tof(lneq1.get_rhs())(y) elif isinstance(lneq1.get_rhs(), pwr): #y = 1x; y = -1x +6 eq1_coeff = get_line_coeffs(lneq1) eq2_coeff = get_line_coeffs(lneq2) if isinstance(lneq2.get_rhs(), plus): if isinstance(lneq2.get_rhs().get_elt2(), const): eq2_const = lneq2.get_rhs().get_elt2().get_val() x = eq2_const / (eq1_coeff - eq2_coeff) y = tof(lneq1.get_rhs())(x) elif isinstance(lneq1.get_rhs(), plus): #y = -0.2x+10; y =0.2x+5 eq1_coeff = get_line_coeffs(lneq1) eq2_coeff = get_line_coeffs(lneq2) if isinstance(lneq2.get_rhs(), plus): x = (lneq2.get_rhs().get_elt2().get_val() + lneq1.get_rhs().get_elt2().get_val()) / (eq1_coeff - eq2_coeff) y = tof(lneq1.get_rhs())(x) else: raise Exception("Unknown plus equation") elif isinstance(lneq1.get_rhs(), prod): #y = 0.5x; y = -0.75x +3 eq1_coeff = get_line_coeffs(lneq1) eq2_coeff = get_line_coeffs(lneq2) if isinstance(lneq2.get_rhs(), plus): eq2_const = lneq2.get_rhs().get_elt2().get_val() x = eq2_const / (eq1_coeff - eq2_coeff) y = tof(lneq1.get_rhs())(x) elif isinstance(lneq2.get_rhs(), pwr): #y = -x, y = x x = 0.0 y = 0.0 else: raise Exception("Unknown prod equation") else: raise Exception('line_intersection: ' + 'unknown equations') return make_point2d(x, y)
def nra(poly_fexpr, g, n): assert isinstance(g, const) assert isinstance(n, const) poly_fexprFunc = tof(poly_fexpr) poly_fexprPrime = deriv(poly_fexpr) poly_fexprPrimeF = tof(poly_fexprPrime) currGuessVal = g.get_val() for i in range(int(n.get_val())): prevVal = currGuessVal currGuessVal = prevVal - (poly_fexprFunc(prevVal) / poly_fexprPrimeF(prevVal)) return currGuessVal
def demand_elasticity(p): assert isinstance(p, const) demand_eq = make_plus(make_const(100), make_prod(make_const(-2.0), make_pwr('p', 1.0))) fx_drv = tof(deriv(demand_eq)) fx = tof(demand_eq) #E(p) = (-p*f'(p)) / f(p) num = (-1.0 * p.get_val()) * fx_drv(p.get_val()) denom = fx(p.get_val()) return num / denom
def test_deriv(fexpr, gt, lwr, uppr, err): assert isinstance(lwr, const) assert isinstance(uppr, const) assert isinstance(err, const) derivfexpr = deriv(fexpr) derivfexprfunc = tof(derivfexpr) gtfunc = tof(gt) for i in range(lwr, uppr): print(derivfexprfunc(i), gtfunc(i)) assert abs(derivfexprfunc(i) - gtfunc(i)) <= err
def loc_xtrm_1st_drv_test(expr): exprFn = tof(expr) derivativeExpr = deriv(expr) derivfn = tof(derivativeExpr) degree = findDegree(derivativeExpr) critical_points = [] if degree == 2: xvalues = find_poly_2_zeros(derivativeExpr) for x in xvalues: y = exprFn(x.get_val()) critical_points.append(make_point2d(x.get_val(), y)) elif degree == 1: x = find_poly_1_zeros(derivativeExpr) y = exprFn(x.get_val()) critical_points.append(make_point2d(x.get_val(), y)) elif degree == 0: # The derivative is just a constant so all values will be just the constant # f` = 5 x = derivativeExpr.get_val() else: raise Exception("Not a first or second degree polynomial degree=", degree) maxima = None minima = None for p in critical_points: x = p.get_x().get_val() less = derivfn(x - 0.5) more = derivfn(x + 0.5) if less < 0 and more > 0: y = exprFn(x) minima = make_point2d(x, y) elif less > 0 and more < 0: y = exprFn(x) maxima = make_point2d(x, y) if not maxima and not minima: return None else: results = [] if maxima: results.append(("max", maxima)) if minima: results.append(("min", minima)) return results
def problem_1_deriv(): # still has problems # f(x) =(x+1)(2x+1)(3x+1) /(4x+1)^.5 fex1 = make_plus(make_pwr('x', 1.0), const(1.0)) fex2 = make_plus(make_prod(const(2.0), make_pwr('x', 1.0)), const(1.0)) fex3 = make_plus(make_prod(const(3.0), make_pwr('x', 1.0)), const(1.0)) fex4 = make_prod(fex1, fex2) fex5 = make_prod(fex4, fex3) fex6 = make_pwr_expr( make_plus(make_prod(const(4.0), make_pwr('x', 1.0)), const(1.0)), 0.5) fex = make_quot(fex5, fex6) print(fex) drv = deriv(fex) print('drv: ', drv) drvf = tof(drv) def gt_drvf(x): n = (60.0 * x**3) + (84 * x**2) + 34 * x + 4 d = (4 * x + 1)**(3 / 2) return n / d for i in range(1, 10): print(drvf(i), gt_drvf(i)) assert abs(gt_drvf(i) - drvf(i)) <= 0.001 assert drv is not None print(drv) # zeros = find_poly_2_zeros(drv) # print(zeros) f1 = tof(fex) f2 = tof(deriv(fex)) xvals = np.linspace(1, 5, 10000) yvals1 = np.array([f1(x) for x in xvals]) yvals2 = np.array([f2(x) for x in xvals]) fig1 = plt.figure(1) fig1.suptitle('Graph') plt.xlabel('x') plt.ylabel('y') plt.ylim() plt.xlim() plt.grid() plt.plot(xvals, yvals1, label=fex.__str__(), c='r') plt.plot(xvals, yvals2, label=deriv(fex).__str__(), c='g') plt.legend(loc='best') plt.show()
def find_infl_pnts(expr): drv = deriv(expr) drv_2 = deriv(drv) # print 'f`(x) = ', drv # print 'f``(x) = ', drv_2 zeros = None try: zeros = find_poly_1_zeros(drv_2) # print '1st degree poly' except Exception: # print 'not a 1st degree poly' pass try: zeros = find_poly_2_zeros(drv_2) # print '2nd degree poly' except Exception: # print 'not a 2nd degree poly' pass if isinstance(zeros, const): zeros = [zeros] # print 'zeros:' # for z in zeros: # print ':',z.get_val() f = tof(expr) f_dp = tof(drv_2) delta = 0.1 points = [] #will store array of points and if they are max/min #zeros may be None if no inflection points if not zeros == None: for z in zeros: z_val = f(z.get_val()) z_minus = f_dp(z.get_val() - delta) z_plus = f_dp(z.get_val() + delta) if z_minus < 0 and z_plus > 0: points.append(point2d(z, const(z_val))) if z_minus > 0 and z_plus < 0: points.append(point2d(z, const(z_val))) else: return None if points == []: return None else: # print points return points
def test_05(): fexpr2_01 = make_prod(make_pwr('x', 1.0), make_e_expr(make_pwr('x', 1.0))) print(gt21_02(2.001)) fex = taylor_poly(fexpr2_01, make_const(2.001), make_const(2)) print(fex) fex_tof = tof(fex) print(fex_tof(2.001))
def loc_xtrm_1st_drv_test(expr): #step 1 take derivative myderiv = deriv(expr) #step2 solve for x zeros = find_poly_2_zeros(myderiv) # for c in zeros: # print c pf = tof(expr) extremas = [] for c in zeros: yval = abs(pf(c.get_val()) - 0.0) if (pf(c.get_val()) - 1 > 0 & pf(c.get_val()) + 1 < 0): extremas.append("min", point2d(c.get_val(), yval)) else: extremas.append("max", point2d(c.get_val(), yval)) return extremas
def problem_3_tangent(): fex = make_e_expr(make_pwr('x', 1.0)) print("f(x)= ", fex) drv = deriv(fex) print("f'(x)= ", drv) drvf = tof(drv) print("f'(-1)= ", drvf(-1))
def test_assign_03_prob_01_ut_04(self): print('\n***** Assign 03: Problem 01: Unit Test 04 *****') e1 = make_pwr('x', 2.0) e2 = make_plus(e1, make_prod(make_const(0.0), make_pwr('x', 1.0))) e3 = make_plus(e2, make_const(-1.0)) e4 = make_pwr_expr(e3, 4.0) e5 = make_pwr('x', 2.0) e6 = make_plus(e5, make_prod(make_const(0.0), make_pwr('x', 1.0))) e7 = make_plus(e6, make_const(1.0)) e8 = make_pwr_expr(e7, 5.0) e9 = make_prod(e4, e8) print(e9) e9f = tof(deriv(e9)) assert not e9f is None err = 0.000001 def drvf(x): return 2 * x * ((x**2 - 1.0)**3) * ( (x**2 + 1.0)**4) * (9 * x**2 - 1.0) for i in range(10): #print(e9f(i), drvf(i)) assert abs(e9f(i) - drvf(i)) <= err print('Assign 03: Problem 01: Unit Test 04: pass')
def test_assign_03_prob_01_ut_06(self): print('\n***** Assign 03: Problem 01: Unit Test 06 *****') e1 = make_prod(make_const(2.0), make_pwr('x', 4.0)) e2 = make_prod(make_const(-1.0), make_pwr('x', 1.0)) e3 = make_plus(e1, e2) e4 = make_plus(e3, make_const(1.0)) e5 = make_prod(make_const(-1.0), make_pwr('x', 5.0)) e6 = make_prod(make_const(0.0), make_pwr('x', 4.0)) e7 = make_plus(e5, e6) e8 = make_prod(make_const(0.0), make_pwr('x', 3.0)) e9 = make_plus(e7, e8) e10 = make_prod(make_const(0.0), make_pwr('x', 2.0)) e11 = make_plus(e9, e10) e12 = make_prod(make_const(0.0), make_pwr('x', 1.0)) e13 = make_plus(e11, e12) e14 = make_plus(e13, make_const(1.0)) e15 = make_prod(e4, e14) print('-- function expression is:\n') print(e15) drv = deriv(e15) assert not drv is None print('\n-- derivative is:\n') print(drv) e15f = tof(drv) assert not e15f is None gt = lambda x: -18.0 * (x**8) + 6.0 * (x**5) - 5.0 * (x**4) + 8.0 * ( x**3) - 1.0 err = 0.00001 print('\n--comparison with ground truth:\n') for i in range(10): #print(e15f(i), gt(i)) assert abs(e15f(i) - gt(i)) <= err print('Assign 03: Problem 01: Unit Test 06: pass')
def test_assign_03_prob_01_ut_05(self): print('\n***** Assign 03: Problem 01: Unit Test 05 *****') e1 = make_plus(make_pwr('x', 1.0), make_const(1.0)) e2 = make_pwr('x', 3.0) e3 = make_prod(make_const(0.0), make_pwr('x', 2.0)) e4 = make_plus(e2, e3) e5 = make_prod(make_const(5.0), make_pwr('x', 1.0)) e6 = make_plus(e4, e5) e7 = make_plus(e6, make_const(2.0)) e8 = make_prod(e1, e7) # 1) print the expression we just constructed print('-- function expression is:\n') print(e8) # 2) differentiate and make sure that it not None drv = deriv(e8) assert not drv is None print('\n-- derivative is:\n') print(e8) # 3) convert drv into a function e8f = tof(drv) assert not e8f is None # steps 2) and 3) can be combined into tof(deriv(e6)). # 4) construct the ground truth function gt = lambda x: 4.0 * (x**3) + 3 * (x**2) + 10.0 * x + 7.0 # 5) compare the ground gruth with what we got in # step 3) on an appropriate number range. print('\n--comparison with ground truth:\n') err = 0.00001 for i in range(15): #print(e8f(i), gt(i)) assert abs(e8f(i) - gt(i)) <= err print('Assign 03: Problem 01: Unit Test 05: pass')