ContentsFoundations to FrontierBezhig

integration_code/solutions/calculus_bridge.py

All lab code. Download this file.

"""W01: exact quadratic rates. Inputs are int or Fraction, not binary floats."""
from dataclasses import dataclass
from fractions import Fraction


def rational(value):
    if type(value) not in (int,Fraction):
        raise TypeError("use an integer or Fraction for this exact lab")
    return Fraction(value)


@dataclass(frozen=True)
class Quadratic:
    a: Fraction
    b: Fraction
    c: Fraction

    def __post_init__(self):
        for key in ('a','b','c'):
            object.__setattr__(self,key,rational(getattr(self,key)))

    def value(self,x):
        x=rational(x)
        return self.a*x*x+self.b*x+self.c

    def average_rate(self,x,h):
        x,h=rational(x),rational(h)
        if h == 0:
            raise ValueError("average rate needs a nonzero interval")
        return (self.value(x+h)-self.value(x))/h

    def tangent(self,x):
        x=rational(x)
        slope=2*self.a*x+self.b
        intercept=self.value(x)-slope*x
        return slope,intercept


if __name__=='__main__':
    f=Quadratic(3,2,-4)
    print('point height:',f.value(-1))
    print('average rate:',f.average_rate(-1,Fraction(1,10)))
    print('tangent slope and intercept:',f.tangent(-1))