Beispiel #1
0
def asfrac(A, limit=None):

    if isinstance(A, (np.ndarray, float, int, long)):
        return f.frac(A, 1, limit)

    elif isinstance(A, f.frac):
        return f.frac(A.a, A.b, limit)

    elif isinstance(A, p.Poly):
        return p.asfrac(A, limit)

    raise NotImplementedError
Beispiel #2
0
def asfrac(A, limit=None):

    if isinstance(A, (np.ndarray, float, int, long)):
        return f.frac(A, 1, limit)

    elif isinstance(A, f.frac):
        return f.frac(A.a, A.b, limit)

    elif isinstance(A, p.Poly):
        return p.asfrac(A, limit)

    raise NotImplementedError
Beispiel #3
0
def asfrac(P, limit=None):
    B = P.A.copy()
    for key in P.keys:
        B[key] = f.frac(B[key], 1, limit)

    out = Poly(B, P.dim, P.shape, f.frac)
    return out
Beispiel #4
0
def asfrac(P, limit=None):
    B = P.A.copy()
    for key in P.keys:
        B[key] = f.frac(B[key], 1, limit)

    out = Poly(B, P.dim, P.shape, f.frac)
    return out
Beispiel #5
0
def around(A, decimals=0):
    """
Evenly round to the given number of decimals.

Parameters
----------
A : p.Poly, f.frac, array_like
    Input data.
decimals : int, optional
    Number of decimal places to round to (default: 0).  If
    decimals is negative, it specifies the number of positions to
    the left of the decimal point.

Returns
-------
Q : p.Poly, f.frac, array_like
    Same type as A.

Examples
--------
>>> P = cp.prange(3)*2**-np.arange(0, 6, 2, float)
>>> print P
[1.0, 0.25q0, 0.0625q0^2]
>>> print cp.around(P)
[1.0, 0.0, 0.0]
>>> print cp.around(P, 2)
[1.0, 0.25q0, 0.06q0^2]
    """
    if isinstance(A, (np.ndarray, float, int, long)):
        return np.around(A, decimals)

    elif isinstance(A, f.frac):

        if decimals >= 0:
            a = (A.a * 10**decimals) // A.b
            return f.frac(a, 10**decimals)
        a = A.a // (A.b * 10**-decimals)
        return f.frac(a * 10**-decimals)

    elif isinstance(A, p.Poly):

        B = A.A.copy()
        for key in A.keys:
            B[key] = around(B[key], decimals)
        return p.Poly(B, A.dim, A.shape, A.dtype)

    raise NotImplementedError
Beispiel #6
0
def around(A, decimals=0):
    """
Evenly round to the given number of decimals.

Parameters
----------
A : p.Poly, f.frac, array_like
    Input data.
decimals : int, optional
    Number of decimal places to round to (default: 0).  If
    decimals is negative, it specifies the number of positions to
    the left of the decimal point.

Returns
-------
Q : p.Poly, f.frac, array_like
    Same type as A.

Examples
--------
>>> P = cp.prange(3)*2**-np.arange(0, 6, 2, float)
>>> print P
[1.0, 0.25q0, 0.0625q0^2]
>>> print cp.around(P)
[1.0, 0.0, 0.0]
>>> print cp.around(P, 2)
[1.0, 0.25q0, 0.06q0^2]
    """
    if isinstance(A, (np.ndarray, float, int, long)):
        return np.around(A, decimals)

    elif isinstance(A, f.frac):

        if decimals>=0:
            a = (A.a*10**decimals)//A.b
            return f.frac(a, 10**decimals)
        a = A.a//(A.b*10**-decimals)
        return f.frac(a*10**-decimals)

    elif isinstance(A, p.Poly):

        B = A.A.copy()
        for key in A.keys:
            B[key] = around(B[key], decimals)
        return p.Poly(B, A.dim, A.shape, A.dtype)

    raise NotImplementedError
Beispiel #7
0
def call(P, args):
    """
Evaluate a polynomial along specified axes.

Parameters
----------
P : Poly
    Input polynomial.
args : array_like, masked
    Argument to be evalutated.
    Masked values keeps the variable intact.

Returns
-------
Q : Poly, np.array
    If masked values are used the Poly is returned. Else an
    numpy array matching the polynomial's shape is returned.
    """

    args = list(args)

    # expand args to match dim
    if len(args)<P.dim:
        args = args + [np.nan]*(P.dim-len(args))
    elif len(args)>P.dim:
        raise ValueError, "too many arguments"

    # Find and perform substitutions, if any
    x0,x1 = [],[]
    for i in xrange(len(args)):

        if isinstance(args[i], Poly):

            x0.append(Poly({tuple(np.eye(P.dim)[i]):np.array(1)}))
            x1.append(args[i])
            args[i] = np.nan
    if x0:
        P = call(P, args)
        return substitute(P, x0, x1)

    # Create masks
    masks = np.zeros(len(args), dtype=bool)
    for i in xrange(len(args)):
        if np.ma.is_masked(args[i]) \
            or np.any(args[i]!=args[i]):
            masks[i] = True
            args[i] = 0

    shape = np.array(args[np.argmax([np.prod(np.array(arg).shape)\
        for arg in args])]).shape
    args = np.array([np.ones(shape, dtype=int)*arg \
        for arg in args])

    A = {}
    for key in P.keys:

        key_ = np.array(key)*(1-masks)
        val = np.outer(P.A[key], np.prod((args.T**key_).T, \
                axis=0))
        val = np.reshape(val, P.shape + tuple(shape))
        val = np.where(val!=val, 0, val)

        mkey = tuple(np.array(key)*(masks))
        if not mkey in A:
            A[mkey] = val
        else:
            A[mkey] = A[mkey] + val
        if P.dtype==f.frac:
            A[mkey] = f.frac(A[mkey])

    out = Poly(A, P.dim, None, None)
    if out.keys and not np.sum(out.keys):
        out = out.A[out.keys[0]]
    elif not out.keys:
        out = np.zeros(out.shape, dtype=out.dtype)
    return out
Beispiel #8
0
    def __init__(self, A=None, dim=None, shape=None,
        dtype=None, V=0):
        """
Parameters
----------
A : array_like, dict, Poly
    The polynomial coefficient Tensor.
    Where A[(i,j,k)] corresponds to a_{ijk} x^i y^j z^k
    (A[i][j][k] for list and tuple)
dim : int
    the dimensionality of the polynomial.
    Automatically set if A contains a value.
shape : tuple
    the number of polynomials represented.
    Automatically set if A contains a value.
dtype : type
    The type of the polynomial coefficients
        """

        if V: print "\nConstruct poly out of:\n", A

        if isinstance(A, Poly):

            dtype_ = A.dtype
            shape_ = A.shape
            dim_ = A.dim
            A = A.A.copy()

        elif isinstance(A, np.ndarray):

            dtype_ = A.dtype
            shape_ = A.shape
            dim_ = 1
            A = {(0,):A}

        elif isinstance(A, (int, long, float)):

            dtype_ = type(A)
            shape_ = ()
            dim_ = 1
            A = {(0,):np.array(A)}

        elif isinstance(A, dict):

            A = A.copy()

            if not A:
                dtype_ = int
                dim_ = 1
                shape_ = ()

            else:
                key = A.keys()[0]
                shape_ = np.array(A[key]).shape
                dim_ = len(key)
                dtype_ = dtyping(A[key])

        elif isinstance(A, f.frac):

            dtype_ = f.frac
            shape_ = A.shape
            dim_ = 1
            if isinstance(A.a, int):
                A = f.frac(np.array(A.a), np.array(A.b))
            A = {(0,): A}

        elif isinstance(A, (np.ndarray, list, tuple)):

            A = [Poly(a) for a in A]
            shape_ = (len(A),) + A[0].shape

            dtype_ = dtyping(*[_.dtype for _ in A])

            dims = np.array([a.dim for a in A])
            dim_ = np.max(dims)
            if dim_!=np.min(dims):
                A = [setdim(a, dim_) for a in A]

            d = {}
            for i in xrange(len(A)): # i over list of polys

                if V: print "Adding:", A[i], "(%d)" % i
                for key in A[i].A: # key over exponents in each poly

                    if not d.has_key(key):
                        if V: print "creating key", key
                        if dtype_==f.frac:
                            d[key] = f.frac(np.zeros(shape_))
                        else:
                            d[key] = np.zeros(shape_, dtype=dtype_)
                    d[key][i] = A[i].A[key]
                    if V: print "update", key, d[key]
            if V: print "creating master dict:\n", d

            A = d

        else:
            raise TypeError, \
                "Poly arg: 'A' is not a valid type " + repr(A)

        if dtype is None:
            dtype = dtype_
        if dtype==int:

            func1 = asint
            if shape is None:
                shape = shape_
            elif np.any(np.array(shape)!=shape_):
                ones = np.ones(shape, dtype=int)
                func1 = lambda x: asint(x*ones)

        elif dtype==f.frac:

            func1 = f.frac
            if shape is None:
                shape = shape_
            elif np.any(np.array(shape)!=shape_):
                ones = np.ones(shape, dtype=int)
                func1 = lambda x: f.frac(x*ones)

        else:

            func1 = lambda x:np.array(x, dtype=dtype)
            if shape is None:
                shape = shape_
            elif np.any(np.array(shape)!=shape_):
                ones = np.ones(shape, dtype=int)
                func1 = lambda x: 1.*x*ones

        func2 = lambda x:x
        if dim is None:
            dim = dim_
        elif dim<dim_:
            func2 = lambda x:x[:dim]
        elif dim>dim_:
            func2 = lambda x:x + (0,)*(dim-dim_)

        d = {}
        for key, val in A.items():
            d[func2(key)] = func1(val)
        A = d

        if isinstance(shape, int):
            shape = (shape,)

        # Remove empty elements
        for key in A.keys()[:]:
            if np.all(A[key]==0):
                del A[key]

        # assert non-empty container
        if not A:
            if dtype==float:
                dt = float
            else:
                dt = int
            A = {(0,)*dim: np.zeros(shape, dtype=dt)}

        self.keys = A.keys()
        self.dim = dim
        self.shape = shape
        self.dtype = dtype
        self.A = A

        if V: print "result", A
Beispiel #9
0
from fraction import frac

x = frac(*map(int, input().split("/")))  # "3/5"のように入力された分数を読み取る
denominators = []  # 分母をこのリストに入れる

# TODO

print("= 1/", end="")
print(*denominators, sep=" + 1/")
Beispiel #10
0
def call(P, args):
    """
Evaluate a polynomial along specified axes.

Parameters
----------
P : Poly
    Input polynomial.
args : array_like, masked
    Argument to be evalutated.
    Masked values keeps the variable intact.

Returns
-------
Q : Poly, np.array
    If masked values are used the Poly is returned. Else an
    numpy array matching the polynomial's shape is returned.
    """

    args = list(args)

    # expand args to match dim
    if len(args) < P.dim:
        args = args + [np.nan] * (P.dim - len(args))
    elif len(args) > P.dim:
        raise ValueError, "too many arguments"

    # Find and perform substitutions, if any
    x0, x1 = [], []
    for i in xrange(len(args)):

        if isinstance(args[i], Poly):

            x0.append(Poly({tuple(np.eye(P.dim)[i]): np.array(1)}))
            x1.append(args[i])
            args[i] = np.nan
    if x0:
        P = call(P, args)
        return substitute(P, x0, x1)

    # Create masks
    masks = np.zeros(len(args), dtype=bool)
    for i in xrange(len(args)):
        if np.ma.is_masked(args[i]) \
            or np.any(args[i]!=args[i]):
            masks[i] = True
            args[i] = 0

    shape = np.array(args[np.argmax([np.prod(np.array(arg).shape)\
        for arg in args])]).shape
    args = np.array([np.ones(shape, dtype=int)*arg \
        for arg in args])

    A = {}
    for key in P.keys:

        key_ = np.array(key) * (1 - masks)
        val = np.outer(P.A[key], np.prod((args.T**key_).T, \
                axis=0))
        val = np.reshape(val, P.shape + tuple(shape))
        val = np.where(val != val, 0, val)

        mkey = tuple(np.array(key) * (masks))
        if not mkey in A:
            A[mkey] = val
        else:
            A[mkey] = A[mkey] + val
        if P.dtype == f.frac:
            A[mkey] = f.frac(A[mkey])

    out = Poly(A, P.dim, None, None)
    if out.keys and not np.sum(out.keys):
        out = out.A[out.keys[0]]
    elif not out.keys:
        out = np.zeros(out.shape, dtype=out.dtype)
    return out
Beispiel #11
0
    def __init__(self, A=None, dim=None, shape=None, dtype=None, V=0):
        """
Parameters
----------
A : array_like, dict, Poly
    The polynomial coefficient Tensor.
    Where A[(i,j,k)] corresponds to a_{ijk} x^i y^j z^k
    (A[i][j][k] for list and tuple)
dim : int
    the dimensionality of the polynomial.
    Automatically set if A contains a value.
shape : tuple
    the number of polynomials represented.
    Automatically set if A contains a value.
dtype : type
    The type of the polynomial coefficients
        """

        if V: print "\nConstruct poly out of:\n", A

        if isinstance(A, Poly):

            dtype_ = A.dtype
            shape_ = A.shape
            dim_ = A.dim
            A = A.A.copy()

        elif isinstance(A, np.ndarray):

            dtype_ = A.dtype
            shape_ = A.shape
            dim_ = 1
            A = {(0, ): A}

        elif isinstance(A, (int, long, float)):

            dtype_ = type(A)
            shape_ = ()
            dim_ = 1
            A = {(0, ): np.array(A)}

        elif isinstance(A, dict):

            A = A.copy()

            if not A:
                dtype_ = int
                dim_ = 1
                shape_ = ()

            else:
                key = A.keys()[0]
                shape_ = np.array(A[key]).shape
                dim_ = len(key)
                dtype_ = dtyping(A[key])

        elif isinstance(A, f.frac):

            dtype_ = f.frac
            shape_ = A.shape
            dim_ = 1
            if isinstance(A.a, int):
                A = f.frac(np.array(A.a), np.array(A.b))
            A = {(0, ): A}

        elif isinstance(A, (np.ndarray, list, tuple)):

            A = [Poly(a) for a in A]
            shape_ = (len(A), ) + A[0].shape

            dtype_ = dtyping(*[_.dtype for _ in A])

            dims = np.array([a.dim for a in A])
            dim_ = np.max(dims)
            if dim_ != np.min(dims):
                A = [setdim(a, dim_) for a in A]

            d = {}
            for i in xrange(len(A)):  # i over list of polys

                if V: print "Adding:", A[i], "(%d)" % i
                for key in A[i].A:  # key over exponents in each poly

                    if not d.has_key(key):
                        if V: print "creating key", key
                        if dtype_ == f.frac:
                            d[key] = f.frac(np.zeros(shape_))
                        else:
                            d[key] = np.zeros(shape_, dtype=dtype_)
                    d[key][i] = A[i].A[key]
                    if V: print "update", key, d[key]
            if V: print "creating master dict:\n", d

            A = d

        else:
            raise TypeError, \
                "Poly arg: 'A' is not a valid type " + repr(A)

        if dtype is None:
            dtype = dtype_
        if dtype in (int, long):

            func1 = asint
            if shape is None:
                shape = shape_
            elif np.any(np.array(shape) != shape_):
                ones = np.ones(shape, dtype=int)
                func1 = lambda x: asint(x * ones)

        elif dtype == f.frac:

            func1 = f.frac
            if shape is None:
                shape = shape_
            elif np.any(np.array(shape) != shape_):
                ones = np.ones(shape, dtype=int)
                func1 = lambda x: f.frac(x * ones)

        else:

            func1 = lambda x: np.array(x, dtype=dtype)
            if shape is None:
                shape = shape_
            elif np.any(np.array(shape) != shape_):
                ones = np.ones(shape, dtype=int)
                func1 = lambda x: 1. * x * ones

        func2 = lambda x: x
        if dim is None:
            dim = dim_
        elif dim < dim_:
            func2 = lambda x: x[:dim]
        elif dim > dim_:
            func2 = lambda x: x + (0, ) * (dim - dim_)

        d = {}
        for key, val in A.items():
            d[func2(key)] = func1(val)
        A = d

        if isinstance(shape, int):
            shape = (shape, )

        # Remove empty elements
        for key in A.keys()[:]:
            if np.all(A[key] == 0):
                del A[key]

        # assert non-empty container
        if not A:
            if dtype == float:
                dt = float
            else:
                dt = int
            A = {(0, ) * dim: np.zeros(shape, dtype=dt)}

        self.keys = A.keys()
        self.dim = dim
        self.shape = shape
        self.dtype = dtype
        self.A = A

        if V: print "result", A
Beispiel #12
0
from fraction import frac

x = frac(*map(int, input().split("/")))  # "3/5"のように入力された分数を読み取ってfracクラスを作る
denominators = []  # 分母をこのリストに入れる

while x.bunsi != 1:
    t = x.bunbo // x.bunsi + 1
    denominators.append(t)
    x = x - frac(1, t)
denominators.append(x.bunbo)

print("= 1/", end="")
print(*denominators, sep=" + 1/")