h$ܽb      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                                                                                                                                 !!!!!!!!!!!!"""""""""""""""""""""""""""""""""""""""""##############################################$$$$%%%%&&&&&&&&&&&&&&&&'''''''''''''''''''''''''''''''''''''''((((())))))))))*******++++++++++++++++++++++,,,,,,,,,,,,,,---------------------....................../////////////////////////////////////////////////////////////000000000000011111111111111111111111111111112222222222222222333333333333333333333333333344444 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 : : : : : : : : : : : : : : : : : : ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; < < < < < < < < < < < < < < < < < < = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = > > > > > > > > > > > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ A A A A A A A A A A A A A A A A A A B B B B B B B B B B B B B B B B C C C C C C C C C C C C C C C C C C C C C C C D D D D D D D D D D D D D D D D D D D D D D D D D D D D D D D D D D E E E E E E E E E E E E E E E E E E E E E E E E E E E E E F F F F F F F F G G G G G G G G G G G G G G G G G G G G G G G G G H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H I I I I I I I I I I I I I J J J J J J J J J J J J J K K K K K K K K K K K K K K K K K K K K K K K K L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L LLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRRRRSSSSSSSSTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUVVVVVVVVVVVVVVVVVVVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWXXXXXXXXXXYYYYYYYYZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ[[[[[[[[[[[[[[[[ Safe-Inferred.numeric-prelude>This class allows defining instances that are exclusively for ; dimension. You won't want to define instances by yourself.>>77(c) Henning Thielemann 2007$numericprelude@henning-thielemann.de provisionalportable Safe-Inferred29numeric-prelude5Wrap an indexable object such that it can be used in Data.Map and Data.Set.numeric-preludeDefinition of an alternative ordering of objects independent from a notion of magnitude. For an application see MathObj.PartialFraction.numeric-preludeIf the type has already an 5 instance it is certainly the most easiest to define  to be equal to Ord's .numeric-preludeLift & implementation from a wrapped object. Safe-Inferred2{\ Safe-Inferred2(c) Henning Thielemann 2006$numericprelude@henning-thielemann.de provisional Safe-Inferred,4Anumeric-preludeThere are quite a few way we could represent elements of permutation groups: the images in a row, a list of the cycles, et.c. All of these differ highly in how complex various operations end up being. Safe-Inferred4w 43 efhg2cbopnTPQSVXURW65(+$*)%./0&',-1789:;<=>?@ABCDEFGHIJKLMNOYZ[\]^_`adijklmqrstuvwxyz{|}~v (+43',- efhg2D&F$*)%./0cbdopnm1HKI9yML|~_RWUXV?=> lt EQ -> eq GT -> gt:for atomic types where the right hand side can be defined. Minimal complete definition:  or .  Safe-Inferred,G numeric-preludeAdditive a encapsulates the notion of a commutative group, specified by the following laws:  a + b === b + a (a + b) + c === a + (b + c) zero + a === a a + negate a === 0 8Typical examples include integers, dollars, and vectors.Minimal definition: , , and ( or )numeric-prelude zero element of the vector spacenumeric-preludeadd and subtract elementsnumeric-preludeadd and subtract elementsnumeric-preludeinverse with respect to numeric-prelude is (-) with swapped operand order. This is the operand order which will be needed in most cases of partial application.numeric-prelude9Sum up all elements of a list. An empty list yields zero.This function is inappropriate for number types like Peano. Maybe we should make , a method of Additive. This would also make  lengthLeft and  lengthRight superfluous.numeric-preludeSum up all elements of a non-empty list. This avoids including a zero which is useful for types where no universal zero is available. ToDo: Should have NonEmpty type.7\(QC.NonEmpty ns) -> A.sum ns == (A.sum1 ns :: Integer)numeric-preludeSum the operands in an order, such that the dependencies are minimized. Does this have a measurably effect on speed?Requires associativity.9\ns -> A.sum ns == (A.sumNestedAssociative ns :: Integer)numeric-preludeMake sure that the last entries in the list are equally often part of an addition. Maybe this can reduce rounding errors. The list that sum2 computes is a breadth-first-flattened binary tree.)Requires associativity and commutativity.9\ns -> A.sum ns == (A.sumNestedCommutative ns :: Integer)numeric-preludeInstead of baking the add operation into the element function, we could use higher rank types and pass a generic  uncurry (+) to the run function. We do not do so in order to stay Haskell 98 at least for parts of NumericPrelude.numeric-prelude addPair :: (Additive.C a, Additive.C b) => (a,b) -> (a,b) -> (a,b) addPair = Elem.run2 $ Elem.with (,) <*>.+ fst <*>.+ sndnumeric-preludeThe Additive instantiations treat lists as prefixes of infinite lists with zero filled tail. This interpretation is not always appropriate. The end of a list may just mean: End of available data. In this case the shortening % semantics would be more appropriate.66444  Safe-Inferred,Jbnumeric-preludeMaybe the naming should be according to Algebra.Unit: Algebra.Zero as module name, and query as method name.numeric-preludeChecks if a number is the zero element. This test is not possible for all  types, since e.g. a function type does not belong to Eq. isZero is possible for some types where (==zero) fails because there is no unique zero. Examples are vector (the length of the zero vector is unknown), physical values (the unit of a zero quantity is unknown), residue class (the modulus is unknown)._ Safe-InferredL&numeric-preludezip two lists using an arbitrary function, the shorter list is padded numeric-preludeApply a function to the last element of a list. If the list is empty, nothing changes.numeric-preludepadding value numeric-prelude8function applied to corresponding elements of the lists numeric-prelude8function applied to corresponding elements of the lists   Safe-Inferred,Pnumeric-preludeRing encapsulates the mathematical structure of a (not necessarily commutative) ring, with the laws  a * (b * c) === (a * b) * c one * a === a a * one === a a * (b + c) === a * b + a * c Typical examples include integers, polynomials, matrices, and quaternions.Minimal definition: , ( or )numeric-preludeThe exponent has fixed type # in order to avoid an arbitrarily limitted range of exponents, but to reduce the need for the compiler to guess the type (default type). In practice the exponent is most oftenly fixed, and is most oftenly 2. Fixed exponents can be optimized away and thus the expensive computation of #3s doesn't matter. The previous solution used a ` constrained type and the exponent was converted to Integer before computation. So the current solution is not less efficient. A variant of & with more flexibility is provided by ab.numeric-prelude8Commutativity need not be satisfied by all instances of . 78  (c) Henning Thielemann 2004-2005$numericprelude@henning-thielemann.de provisionalportable Safe-Inferred,Stnumeric-preludeWe need a Haskell 98 type class which provides equality test for Vector type constructors.numeric-preludeA Module over a ring satisfies:  a *> (b + c) === a *> b + a *> c (a * b) *> c === a *> (b *> c) (a + b) *> c === a *> c + b *> cnumeric-prelude zero element of the vector spacenumeric-preludeadd and subtract elementsnumeric-preludescale a vector by a scalarnumeric-prelude4Compute the linear combination of a list of vectors.  467 Safe-Inferred,>S77(c) Henning Thielemann 2009-2010, Mikael Johansson 2006$numericprelude@henning-thielemann.de provisional Safe-InferredUnumeric-preludeWe expect a monoid to adher to associativity and the identity behaving decently. Nothing more, really.(c) Mikael Johansson 2006mik@math.uni-jena.de provisional%requires multi-parameter type classes Safe-Inferred,U (c) Henning Thielemann 2007-2010haskell@henning-thielemann.destable Haskell 98 Safe-Inferred]numeric-preludeInstances of this class must ensure non-negative values. We cannot enforce this by types, but the type class constraint  NonNegative.C avoids accidental usage of types which allow for negative numbers.9The Monoid superclass contributes a zero and an addition.numeric-preludesplit x y == (m,(b,d)) means that  b == (x<=y),  m == min x y, d == max x y - min x y , that is  d == abs(x-y).We have chosen this function as base function, since it provides comparison and subtraction in one go, which is important for replacing common structures like #if x<=y then f(x-y) else g(y-x)that lead to a memory leak for peano numbers. We have choosen the simple check x<=y instead of a full-blown compare, since we want Zero <= undefined3 for peano numbers. Because of undefined values . is in general not commutative in the sense let (m0,(b0,d0)) = split x y (m1,(b1,d1)) = split y x in m0==m1 && d0==d1The result values are in the order in which they are generated for Peano numbers. We have chosen the nested pair instead of a triple in order to prevent a memory leak that occurs if you only use b and d and ignore m. This is demonstrated by test cases Chunky.splitSpaceLeak3 and Chunky.splitSpaceLeak4.numeric-prelude,Default implementation for wrapped types of  and  class.numeric-prelude x -| y == max 0 (x-y)The default implementation is not efficient, because it compares the values and then subtracts, again, if safe.  max 0 (x-y) is more elegant and efficient but not possible in the general case, since x-y% may already yield a negative number.66 Safe-Inferred,gH numeric-preludeIntegralDomain* corresponds to a commutative ring, where a  b7 picks a canonical element of the equivalence class of a in the ideal generated by b.  and  satisfy the laws  a * b === b * a (a `div` b) * b + (a `mod` b) === a (a+k*b) `mod` b === a `mod` b 0 `mod` b === 0Typical examples of IntegralDomain include integers and polynomials over a field. Note that for a field, there is a canonical instance defined by the above rules; e.g., instance IntegralDomain.C Rational where divMod a b = if isZero b then (undefined,a) else (a\/b,0)It shall be noted, that , ,  have a parameter order which is unfortunate for partial application. But it is adapted to mathematical conventions, where the operators are used in infix notation.Minimal definition:  or ( and )numeric-prelude\n (QC.NonZero m) -> let (q,r) = divMod n m in n == (q*m+r :: Integer)numeric-prelude'decomposeVarPositional [b0,b1,b2,...] x decomposes x3 into a positional representation with mixed bases x0 + b0*(x1 + b1*(x2 + b2*x3)) E.g. 1decomposeVarPositional (repeat 10) 123 == [3,2,1]numeric-preludeReturns the result of the division, if divisible. Otherwise undefined.numeric-preludeReturns the result of the division, if divisible. Otherwise undefined.numeric-preludeAllows division by zero. If the divisor is zero, then the dividend is returned as remainder.numeric-prelude roundDown n m rounds n down to the next multiple of m . That is,  roundDown n m is the greatest multiple of m that is at most n). The parameter order is consistent with div; and friends, but maybe not useful for partial application.>\n (QC.NonZero m) -> div n m * m == (roundDown n m :: Integer)numeric-prelude roundUp n m rounds n up to the next multiple of m . That is,  roundUp n m is the greatest multiple of m that is at most n.>\n (QC.NonZero m) -> divUp n m * m == (roundUp n m :: Integer)\n (QC.Positive m) -> let x = roundDown n m in n-m < x && x <= (n :: Integer)\n (QC.NonZero m) -> - roundDown n m == (roundUp (-n) m :: Integer)numeric-prelude divUp n m is similar to div* but it rounds up the quotient, such that divUp n m * m = roundUp n m.77 Safe-Inferred,knumeric-prelude2This class lets us deal with the units in a ring.  tells whether an element is a unit. The other operations let us canonically write an element as a unit times another element. Two elements a, b of a ring R are _associates_ if a=b*u for a unit u. For an element a, we want to write it as a=b*u where b is an associate of a. The map (a->b) is called StandardAssociate by Gap, "unitCanonical" by Axiom, and "canAssoc" by DoCon. The map (a->u) is called "canInv" by DoCon and "unitNormal(x).unit" by Axiom. The laws are  stdAssociate x * stdUnit x === x stdUnit x * stdUnitInv x === 1 isUnit u ==> stdAssociate x === stdAssociate (x*u) Currently some algorithms assume 6 stdAssociate(x*y) === stdAssociate x * stdAssociate yMinimal definition:  and ( or ) and optionally numeric-prelude0Currently some algorithms assume this property.  Safe-Inferred,w numeric-preludeA principal ideal domain is a ring in which every ideal (the set of multiples of some generating set of elements) is principal: That is, every element can be written as the multiple of some generating element. gcd a b. gives a generator for the ideal generated by a and b%. The algorithm above works whenever mod x y, is smaller (in a suitable sense) than both x and y*; otherwise the algorithm may run forever.Laws:  divides x (lcm x y) x `gcd` (y `gcd` z) == (x `gcd` y) `gcd` z gcd x y * z == gcd (x*z) (y*z) gcd x y * lcm x y == x * y(etc: canonical)Minimal definition: * nothing, if the standard Euclidean algorithm work * if  is implemented customly,  and  make use of itnumeric-preludeCompute the greatest common divisor and solve a respective Diophantine equation.  (g,(a,b)) = extendedGCD x y ==> g==a*x+b*y && g == gcd x yTODO: This method is not appropriate for the PID class, because there are rings like the one of the multivariate polynomials, where for all x and y greatest common divisors of x and y exist, but they cannot be represented as a linear combination of x and y. TODO: The definition of extendedGCD does not return the canonical associate.numeric-prelude*The Greatest Common Divisor is defined by:  gcd x y == gcd y x divides z x && divides z y ==> divides z (gcd x y) (specification) divides (gcd x y) xnumeric-preludeLeast common multiplenumeric-preludeCompute the greatest common divisor for multiple numbers by repeated application of the two-operand-gcd.numeric-prelude"A variant with small coefficients.Just (a,b) = diophantine z x y means  a*x+b*y = z. It is required that  gcd(y,z)  x.numeric-preludeLike , but a is minimal with respect to the measure function of the Euclidean algorithm.numeric-preludenumeric-prelude8Not efficient enough, because GCD/LCM is computed twice.numeric-preludeFor Just (n,b) = chineseRemainderMulti [(m0,a0), (m1,a1), ..., (mk,ak)] and all x with  x = b mod n, the congruences *x=a0 mod m0, x=a1 mod m1, ..., x=ak mod mk are fulfilled. Also, n' is the least common multiplier of all mi.;PID.chineseRemainderMulti [(100,21), (10000,2021::Integer)]Just (10000,2021) case PID.chineseRemainderMulti xs of Nothing -> True; Just (n,b) -> abs n == abs (foldl lcm 1 (map fst xs)) && map snd xs == map (mod b . fst) xs\(QC.NonEmpty ms) b -> let xs = map (\(QC.NonZero m) -> (m, mod b m)) ms in case PID.chineseRemainderMulti xs of Nothing -> False; Just (n,c) -> abs n == abs (foldl lcm 1 (map QC.getNonZero ms)) && mod b n == (c::Integer) Safe-Inferred,y}numeric-preludeNothing is the smallest element.numeric-preludeNothing is the largest element.numeric-prelude-It is only a monoid for non-negative numbers. idt <*> GCD (-2) = GCD 24Thus, use this Monoid only for non-negative numbers!   Safe-Inferred,znumeric-prelude is a general differentation operation It must fulfill the Leibnitz condition  differentiate (x * y) == differentiate x * y + x * differentiate yUnfortunately, this scheme cannot be easily extended to more than two variables, e.g. MathObj.PowerSeries2. Safe-Inferred,^numeric-preludeThis is the type class of a ring with a notion of an absolute value, satisfying the laws  a * b === b * a a /= 0 => abs (signum a) === 1 abs a * signum a === aMinimal definition: , .If the type is in the  class we expect  =  and  = * and we expect the following laws to hold:  a + (max b c) === max (a+b) (a+c) negate (max b c) === min (negate b) (negate c) a * (max b c) === max (a*b) (a*c) where a >= 0 absOrd a === max a (-a)If the type is  ZeroTestable, then it should hold - isZero a === signum a == signum (negate a)We do not require * as superclass since we also want to have Number.Complex% as instance. We also do not require  ZeroTestable as superclass, because we like to have expressions of foreign languages to be instances (cf. embedded domain specific language approach, EDSL), as well as function types. for complex numbers alone may have an inappropriate type, because it does not reflect that the absolute value is a real number. You might prefer Lc. This type class is intended for unifying algorithms that work for both real and complex numbers. Note the similarity to  Algebra.Units:  plays the role of  stdAssociate and  plays the role of stdUnit.Actually, since  can be defined using  and $ we could relax the superclasses to Additive and ! if his class would only contain .(c) Henning Thielemann 2011-2012 (c) Dylan Thurston 2006$numericprelude@henning-thielemann.de provisional portable (?) Safe-Inferred,-numeric-prelude similar to #d numeric-preludeThis is an alternative show method that is more user-friendly but also potentially more ambigious.numeric-preludeNecessary when mixing NumericPrelude.Numeric Rationals with Prelude98 Rationals  7 Safe-Inferred,numeric-preludeField again corresponds to a commutative ring. Division is partially defined and satisfies  not (isZero b) ==> (a * b) / b === a not (isZero a) ==> a * recip a === onewhen it is defined. To safely call division, the program must take type-specific action; e.g., the following is appropriate in many cases: safeRecip :: (Integral a, Eq a, Field.C a) => a -> Maybe a safeRecip x = let (q,r) = one `divMod` x in toMaybe (isZero r) qTypical examples include rationals, the real numbers, and rational functions (ratios of polynomial functions). An instance should be typically declared only if most elements are invertible.Actually, we have also used this type class for non-fields containing lots of units, e.g. residue classes with respect to non-primes and power series. So the restriction not (isZero a) must be better isUnit a.Minimal definition:  or ()numeric-prelude*Needed to work around shortcomings in GHC.numeric-prelude)the restriction on the divisor should be isUnit a instead of not (isZero a)78None,cnumeric-preludeThis class allows lossless conversion from any representation of a rational to the fixed  type. "Lossless" means - don't do any rounding. For rounding see Algebra.RealRing. With the instances for ! and   we acknowledge that these types actually represent rationals rather than (approximated) real numbers. However, this contradicts to the ef class.)Laws that must be satisfied by instances: " fromRational' . toRational === idnumeric-prelude=Lossless conversion from any representation of a rational to numeric-preludeIt should hold (realToField = fromRational' . toRationalbut it should be much more efficient for particular pairs of types, such as converting ! to  #. This achieved by optimizer rules. Safe-Inferred,numeric-preludeRemember that  does not specify exactly what a  b should be, mainly because there is no sensible way to define it in general. For an instance of Algebra.RealIntegral.C a, it is expected that a  b will round towards 0 and a gh b# will round towards minus infinity.$Minimal definition: nothing required77Nonenumeric-preludeThe two classes  and ` exist to allow convenient conversions, primarily between the built-in types. They should satisfy  fromInteger . toInteger === id toRational . toInteger === toRationalConversions must be lossless, that is, they do not round in any way. For rounding see Algebra.RealRing.I think that the RealIntegral superclass is too restrictive. Non-negative numbers are not a ring, but can be easily converted to Integers.numeric-preludeA prefix function of  with a parameter order that fits the needs of partial application and function composition. It has generalised exponent.See: Argument order of expNat on http://www.haskell.org/pipermail/haskell-cafe/2006-September/018022.htmlnumeric-preludeA prefix function of  . It has a generalised exponent.0(c) Dylan Thurston, Henning Thielemann 2004-2005$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone,>Inumeric-preludeA Module over a ring satisfies:  a *> (b + c) === a *> b + a *> c (a * b) *> c === a *> (b *> c) (a + b) *> c === a *> c + b *> cnumeric-preludescale a vector by a scalarnumeric-prelude4Compute the linear combination of a list of vectors.ToDo: Should it use (i ?numeric-prelude(This function can be used to define any  as a module over #.Better move to Algebra.Additive?7None,>None,>enumeric-preludeDivisibleSpace is used for free one-dimensional vector spaces. It satisfies  (a b) *> b = a(Examples include dollars and kilometers.7 $numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone,>numeric-prelude It must hold:  Module.linearComb (flatten v `asTypeOf` [a]) (basis a) == v dimension a v == length (flatten v `asTypeOf` [a])numeric-preludebasis of the module with respect to the scalar type, the result must be independent of argument, gj should suffice. numeric-preludescale a vector by a scalarnumeric-preludethe size of the basis, should also work for undefined argument, the result must be independent of argument, gj should suffice. !None,~numeric-preludeMinimal implementation:  or (^\/).  8"None,numeric-preludeTranscendental is the type of numbers supporting the elementary transcendental functions. Examples include real numbers, complex numbers, and computable reals represented as a lazy list of rational approximations.Note the default declaration for a superclass. See the comments below, under "Instance declaractions for superclasses".The semantics of these operations are rather ill-defined because of branch cuts, etc.Minimal complete definition: pi, exp, (log or logBase), sin, cos, atan''88#None,numeric-prelude"Minimal complete definition:  or /There are probably more laws, but some laws are splitFraction x === (fromInteger (floor x), fraction x) fromInteger (floor x) + fraction x === x floor x <= x x < floor x + 1 ceiling x - 1 < x x <= ceiling x 0 <= fraction x fraction x < 1  - ceiling x === floor (-x) truncate x === signum x * floor (abs x) ceiling (toRational x) === ceiling x :: Integer truncate (toRational x) === truncate x :: Integer floor (toRational x) === floor x :: IntegerThe new function  doesn't return the integer part of the number. This also removes a type ambiguity if the integer part is not needed.Many people will associate rounding with fractional numbers, and thus they are surprised about the superclass being Ring not Field. The reason is that all of these methods can be defined exclusively with functions from Ord and Ring. The implementations of  and other functions demonstrate that. They implement power-of-two-algorithms like the one for finding the number of digits of an # in FixedPoint-fractions module. They are even reasonably efficient.I am still uncertain whether it was a good idea to add instances for Integer and friends, since calling floor or fraction on an integer may well indicate a bug. The rounding functions are just the identity function and  is constant zero. However, I decided to associate our class with Ring rather than Field, after I found myself using repeated subtraction and testing rather than just calling fraction&, just in order to get the constraint (Ring a, Ord a) that was more general than  (RealField a).For the results of the rounding functions we have chosen the constraint Ring instead of  ToInteger, since this is more flexible to use, but it still signals to the user that only integral numbers can be returned. This is so, because the plain Ring class only provides zero, one and operations that allow to reach all natural numbers but not more.2As an aside, let me note the similarities between splitFraction x and  divMod x 1 (if that were defined). In particular, it might make sense to unify the rounding modes somehow.The new methods  and  differ from gk! semantics. They always round to . This means that the fraction is always non-negative and is always smaller than 1. This is more useful in practice and can be generalised to more than real numbers. Since every  denominator type supports , every  can provide  and -, e.g. fractions of polynomials. However the Ring constraint for the ' integral' part of  is too weak in order to generate polynomials. After all, I am uncertain whether this would be useful or not."Can there be a separate class for , ,  and 1 since they do not need reals and their ordering?We might also add a round method, that rounds 0.5 always up or always down. This is much more efficient in inner loops and is acceptable or even preferable for many applications.numeric-prelude\x -> (x::Rational) == (uncurry (+) $ mapFst fromInteger $ splitFraction x)\x -> uncurry (==) $ mapFst (((x::Double)-) . fromInteger) $ splitFraction x\x -> uncurry (==) $ mapFst (((x::Rational)-) . fromInteger) $ splitFraction x\x -> splitFraction x == (floor (x::Double) :: Integer, fraction x)\x -> splitFraction x == (floor (x::Rational) :: Integer, fraction x)numeric-prelude1\x -> let y = fraction (x::Double) in 0<=y && y<13\x -> let y = fraction (x::Rational) in 0<=y && y<1numeric-prelude;\x -> ceiling (-x) == negate (floor (x::Double) :: Integer)=\x -> ceiling (-x) == negate (floor (x::Rational) :: Integer)numeric-prelude;\x -> ceiling (-x) == negate (floor (x::Double) :: Integer)=\x -> ceiling (-x) == negate (floor (x::Rational) :: Integer)numeric-prelude1This function rounds to the closest integer. For fraction x == 0.5 it rounds away from zero. This function is not the result of an ingenious mathematical insight, but is simply a kind of rounding that is the fastest on IEEE floating point architectures.numeric-prelude6TODO: Should be moved to a continued fraction module. numeric-preludeThe generic rounding functions need a number of operations proportional to the number of binary digits of the integer portion. If operations like multiplication with two and comparison need time proportional to the number of binary digits, then the overall rounding requires quadratic time.9RealRing.genericFloor =~= (NP.floor :: Double -> Integer);RealRing.genericFloor =~= (NP.floor :: Rational -> Integer)numeric-prelude=RealRing.genericCeiling =~= (NP.ceiling :: Double -> Integer)?RealRing.genericCeiling =~= (NP.ceiling :: Rational -> Integer)numeric-prelude?RealRing.genericTruncate =~= (NP.truncate :: Double -> Integer)RealRing.genericTruncate =~= (NP.truncate :: Rational -> Integer)numeric-prelude9RealRing.genericRound =~= (NP.round :: Double -> Integer);RealRing.genericRound =~= (NP.round :: Rational -> Integer)numeric-prelude>RealRing.genericFraction =~= (NP.fraction :: Double -> Double)RealRing.genericFraction =~= (NP.fraction :: Rational -> Rational)numeric-preludeRealRing.genericSplitFraction =~= (NP.splitFraction :: Double -> (Integer,Double))RealRing.genericSplitFraction =~= (NP.splitFraction :: Rational -> (Integer,Rational))numeric-prelude7Needs linear time with respect to the number of digits.2This and other functions using OrderDecision like floor where argument and result are the same may be moved to a new module.!!$None,numeric-preludeThis is a convenient class for common types that both form a field and have a notion of ordering by magnitude.%None,numeric-preludeThis class collects all functions for _scalar_ floating point numbers. E.g. computing 7 for complex floating numbers makes certainly no sense.&None,Enumeric-preludeCounterpart of gl$ but with NumericPrelude superclass.'None}numeric-preludeThis makes a type usable in the NumericPrelude framework that was initially implemented for Haskell98 typeclasses. E.g. if a is in class , then T a is both in class  and in .&You can even lift container types. If  Polynomial a is in  for all types a that are in , then 3T (Polynomial (MathObj.Wrapper.NumericPrelude.T a)) is in  for all types a that are in .(None,Unumeric-preludeTaken number of elements must be at most the length of the list, otherwise the end of the list is undefined.numeric-preludeDropped number of elements must be at most the length of the list, otherwise the end of the list is undefined.numeric-preludeSplit position must be at most the length of the list, otherwise the end of the first list and the second list are undefined.numeric-preludeThe index must be smaller than the length of the list, otherwise the result is undefined.numeric-preludeZip two lists which must be of the same length. This is checked only lazily, that is unequal lengths are detected only if the list is evaluated completely. But it is more strict than zipWithPad undefined f< since the latter one may succeed on unequal length list if f is lazy.numeric-prelude8function applied to corresponding elements of the lists )None,inumeric-preludeLeft associative length computation that is appropriate for types like Integer.numeric-preludeRight associative length computation that is appropriate for types like Peano number.  None, !"##"! *None,numeric-preludeThe division may be ambiguous. In this case an arbitrary quotient is returned. 0:4 * 2 :4 == 0/:4 2:4 * 2 :4 == 0/:4 +None,numeric-preludeT is a Reader monad but does not need functional dependencies like that from the Monad Transformer Library.,None,numeric-prelude+Here we try to provide implementations for  and  by making the modulus optional. We have to provide non-modulus operations for the cases where both operands have Nothing modulus. This is problematic since operations like (\/)# depend essentially on the modulus. A working version with disabled  and  can be found ResidueClass.numeric-prelude=the modulus can be Nothing to denote a generic constant like  and 6 which could not be bound to a specific modulus so farnumeric-preluder /: m! is the residue class containing r with respect to the modulus mnumeric-prelude3Check if two residue classes share the same modulus  77-None,knumeric-preludeHere a residue class is a representative and the modulus is an argument. You cannot show a value of type , you can only show it with respect to a concrete modulus. Values cannot be compared, because the comparison result depends on the modulus..None,numeric-preludeThe best solution seems to let  be part of the type. This could happen with a phantom type for modulus and a run function like mn. Then operations with non-matching moduli could be detected at compile time and  and  could be generated with the correct modulus. An alternative trial can be found in module ResidueClassMaybe.numeric-preluder /: m! is the residue class containing r with respect to the modulus mnumeric-prelude3Check if two residue classes share the same modulus77/ (c) Henning Thielemann 2007-2012$numericprelude@henning-thielemann.de provisionalportableNone,Znumeric-prelude3If all values are completely defined, then it holds "if b then x else y == ifLazy b x y However if b is undefined, then it is at least known that the result is larger than min x y.numeric-preludecf. To how to find the shortest list in a list of lists efficiently, this means, also in the presence of infinite lists. http://www.haskell.org/pipermail/haskell-cafe/2006-October/018753.htmlnumeric-prelude*On equality the first operand is returned.numeric-prelude*On equality the first operand is returned.numeric-preludex0 <= x1 && x1 <= x2 ... / for possibly infinite numbers in finite lists.numeric-preludeIn glue x y == (z,(b,r)) z represents min x y, r represents max x y - min x y, and  x<=y == b.Cf. Numeric.NonNegative.Chunkynumeric-preludeCompute  with minimal costs.!!30None,1 (c) Henning Thielemann 2007-2010haskell@henning-thielemann.destable Haskell 98Nonenumeric-preludeA chunky non-negative number is a list of non-negative numbers. It represents the sum of the list elements. It is possible to represent a finite number with infinitely many chunks by using an infinite number of zeros.Note the following problems:>Addition is commutative only for finite representations. E.g. let y = min (1+y) 2 in y is defined, let y = min (y+1) 2 in y is not.The type is equivalent to op.numeric-preludeRemove zero chunks.numeric-preludedivModLazy accesses the divisor in a lazy way. However this is only relevant if the dividend is smaller than the divisor. For large dividends the divisor will be accessed multiple times but since it is already fully evaluated it could also be strict.numeric-preludeThis function has a strict divisor and maintains the chunk structure of the dividend at a smaller scale.numeric-prelude is implemented in terms of . If it is needed we could also provide a function that accesses the divisor first in a lazy way and then uses a strict divisor for subsequent rounds of the subtraction loop. This way we can handle the cases "dividend smaller than divisor" and "dividend greater than divisor" in a lazy and efficient way. However changing the way of operation within one number is also not nice.  (c) Henning Thielemann 2007haskell@henning-thielemann.destable Haskell 98None,numeric-preludeConvert a number to a non-negative number. If a negative number is given, an error is raised.numeric-preludeConvert a number to a non-negative number. A negative number will be replaced by zero. Use this function with care since it may hide bugs.numeric-prelude=name of the calling function to be used in the error message  2None,ԑnumeric-preludeLaws.identity (+) zero . gfLaws.commutative (+) . gfLaws.associative (+) . gf!Laws.inverse (+) negate zero . gf"\x -> Laws.inverse (+) (x-) (gf x)Laws.identity (*) one . gfLaws.commutative (*) . gfLaws.associative (*) . gf3\y -> gf y /= zero ==> Laws.inverse (*) recip one y2\y x -> gf y /= zero ==> Laws.inverse (*) (x/) x y3None, numeric-prelude6Horner's scheme for evaluating a polynomial in a ring.numeric-prelude8Horner's scheme for evaluating a polynomial in a module.numeric-prelude9It's also helpful to put a polynomial in canonical form. + strips leading coefficients that are zero.numeric-prelude*Multiply by the variable, used internally.numeric-prelude\(QC.NonEmpty xs) (QC.NonEmpty ys) -> PolyCore.tensorProduct xs ys == List.transpose (PolyCore.tensorProduct ys (intPoly xs))numeric-prelude7 is fast if the second argument is a short polynomial, 9q relies on that fact.numeric-prelude\xs ys -> PolyCore.equal (intPoly $ PolyCore.mul xs ys) (PolyCore.mulShear xs ys)numeric-prelude\x y -> case (PolyCore.normalize x, PolyCore.normalize y) of (nx, ny) -> not (null (ratioPoly ny)) ==> mapSnd PolyCore.normalize (PolyCore.divMod nx ny) == mapPair (PolyCore.normalize, PolyCore.normalize) (PolyCore.divMod x y)\x y -> not (isZero (ratioPoly y)) ==> let z = fst $ PolyCore.divMod (Poly.coeffs x) y in PolyCore.normalize z == z\x y -> case PolyCore.normalize $ ratioPoly y of ny -> not (null ny) ==> List.length (snd $ PolyCore.divMod x y) < List.length nynumeric-preludeThe modulus will always have one element less than the divisor. This means that the modulus will be denormalized in some cases, e.g. mod [2,1,1] [1,1,1] == [1,0] instead of [1].numeric-preludeIntegrates if it is possible to represent the integrated polynomial in the given ring. Otherwise undefined coefficients occur.4None,Y numeric-prelude"For the series of a real function f compute the series for  x -> f (-x) numeric-prelude"For the series of a real function f compute the series for x -> (f x + f (-x)) / 2 numeric-prelude"For the series of a real function f compute the real series for x -> (f (i*x) + f (-i*x)) / 2 numeric-preludeFor power series of f x, compute the power series of f(x^n).QC.choose (1,10) /\ \m -> QC.choose (1,10) /\ \n xs -> equalTrunc 100 (PS.insertHoles m $ PS.insertHoles n xs) (PS.insertHoles (m*n) xs) numeric-preludeDivide two series where the absolute term of the divisor is non-zero. That is, power series with leading non-zero terms are the units in the ring of power series.Knuth: Seminumerical algorithms numeric-prelude8Divide two series also if the divisor has leading zeros. numeric-preludeWe need to compute the square root only of the first term. That is, if the first term is rational, then all terms of the series are rational.4equalTrunc 50 PSE.sqrtExpl (PS.sqrt (\1 -> 1) [1,1])equalTrunc 500 (1:1:repeat 0) (PS.sqrt (\1 -> 1) (PS.mul [1,1] [1,1]))#checkHoles 50 (PS.sqrt (\1 -> 1)) 1 numeric-preludeInput series must start with a non-zero term, even better with a positive one.equalTrunc 100 (PSE.powExpl (-1/3)) (PS.pow (\1 -> 1) (-1/3) [1,1])equalTrunc 50 (PSE.powExpl (-1/3)) (PS.exp (\0 -> 1) (PS.scale (-1/3) PSE.log))(checkHoles 30 (PS.pow (\1 -> 1) (1/3)) 1(checkHoles 30 (PS.pow (\1 -> 1) (2/5)) 1 numeric-preludeThe first term needs a transcendent computation but the others do not. That's why we accept a function which computes the first term. (exp . x)' = (exp . x) * x' (sin . x)' = (cos . x) * x' (cos . x)' = - (sin . x) * x'3equalTrunc 500 PSE.expExpl (PS.exp (\0 -> 1) [0,1])8equalTrunc 100 (1:1:repeat 0) (PS.exp (\0 -> 1) PSE.log)"checkHoles 30 (PS.exp (\0 -> 1)) 0 numeric-prelude7equalTrunc 500 PSE.sinExpl (PS.sin (\0 -> (0,1)) [0,1]) (0,1)) PSE.asin)&checkHoles 20 (PS.sin (\0 -> (0,1))) 0 numeric-prelude7equalTrunc 500 PSE.cosExpl (PS.cos (\0 -> (0,1)) [0,1])&checkHoles 20 (PS.cos (\0 -> (0,1))) 0 numeric-prelude6equalTrunc 50 PSE.tanExpl (PS.tan (\0 -> (0,1)) [0,1]) (0,1)) PSE.atan)&checkHoles 20 (PS.tan (\0 -> (0,1))) 0 numeric-prelude+Input series must start with non-zero term.3equalTrunc 500 PSE.logExpl (PS.log (\1 -> 0) [1,1])8equalTrunc 100 (0:1:repeat 0) (PS.log (\1 -> 0) PSE.exp)"checkHoles 30 (PS.log (\1 -> 0)) 1 numeric-prelude Computes (log x)' , that is x'/x numeric-prelude1equalTrunc 500 PSE.atan (PS.atan (\0 -> 0) [0,1])8equalTrunc 50 (0:1:repeat 0) (PS.atan (\0 -> 0) PSE.tan)#checkHoles 20 (PS.atan (\0 -> 0)) 0 numeric-preludeequalTrunc 100 (0:1:repeat 0) (PS.asin (\1 -> 1) (\0 -> 0) PSE.sin):equalTrunc 50 PSE.asin (PS.asin (\1 -> 1) (\0 -> 0) [0,1])-checkHoles 30 (PS.asin (\1 -> 1) (\0 -> 0)) 0 numeric-prelude9Would be a nice test, but we cannot compute exactly with : =equalTrunc 50 PSE.acos (PS.acos (\1 -> 1) (\0 -> pi/2) [0,1]) numeric-preludeSince the inner series must start with a zero, the first term is omitted in y. numeric-preludeCompose two power series where the outer series can be developed for any expansion point. To be more precise: The outer series must be expanded with respect to the leading term of the inner series. numeric-preludeThis function returns the series of the inverse function in the form: (point of the expansion, power series)."That is, say we have the equation:  y = a + f(x)where function f is given by a power series with f(0) = 0. We want to solve for x:  x = f^-1(y-a) If you pass the power series of a+f(x) to   , you get  (a, f^-1) as answer, where f^-1 is a power series.The linear term of f (the coefficient of x) must be non-zero.This needs cubic run-time and thus is exceptionally slow. Computing inverse series for special power series might be faster.genInvertible /\ \xs -> let (y,ys) = PS.inv xs; (z,zs) = PS.invDiff xs in y==z && equalTrunc 15 ys zs( ( 5None, numeric-prelude\m n -> equalTrunc 30 (PS.mul (PSE.pow m) (PSE.pow n)) (PSE.pow (m+n)) numeric-prelude%equalTrunc 500 PSE.expExpl PSE.expODE numeric-prelude%equalTrunc 500 PSE.sinExpl PSE.sinODE numeric-prelude%equalTrunc 500 PSE.cosExpl PSE.cosODE numeric-prelude$equalTrunc 50 PSE.tanExpl PSE.tanODE numeric-prelude*equalTrunc 50 PSE.tanExpl PSE.tanExplSieve numeric-prelude%equalTrunc 500 PSE.logExpl PSE.logODE numeric-prelude'equalTrunc 500 PSE.atanExpl PSE.atanODE numeric-prelude'equalTrunc 500 PSE.sinhExpl PSE.sinhODE numeric-prelude'equalTrunc 500 PSE.coshExpl PSE.coshODE numeric-prelude)equalTrunc 500 PSE.atanhExpl PSE.atanhODE numeric-prelude>\expon -> equalTrunc 50 (PSE.powODE expon) (PSE.powExpl expon) numeric-prelude'equalTrunc 100 PSE.sqrtExpl PSE.sqrtODE numeric-prelude8Power series of error function (almost). More precisely 1 erf = 2 / sqrt pi * integrate (x -> exp (-x^2)) , with  erf 0 = 0. numeric-prelude(equalTrunc 50 PSE.tanODE PSE.tanODESieve numeric-prelude3equalTrunc 50 PSE.asinODE (snd $ PS.inv PSE.sinODE)+ + 6(c) Henning Thielemann 2006$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone,M numeric-preludedenominator conversion numeric-preludevery efficient because it can make use of the decimal output of o  7None, numeric-preludedenominator conversion  8None, numeric-preludeExample for a linear equation: Setup a differential equation for y with  y t = (exp (-t)) * (sin t) y' t = -(exp (-t)) * (sin t) + (exp (-t)) * (cos t) y'' t = -2 * (exp (-t)) * (cos t)Thus the differential equation  y'' = -2 * (y' + y)holds.4The following function generates a power series for exp (-t) * sin t& by solving the differential equation. numeric-preludeWe are not restricted to linear equations! Let the solution be y with y t = (1-t)^-1 y' t = (1-t)^-2 y'' t = 2*(1-t)^-3 then it holds y'' = 2 * y' * y  9None,> numeric-prelude"Evaluate (truncated) power series. numeric-prelude"Evaluate (truncated) power series. numeric-preludeEvaluate approximations that is evaluate all truncations of the series. numeric-preludeEvaluate approximations that is evaluate all truncations of the series. numeric-preludeEvaluate approximations that is evaluate all truncations of the series. numeric-preludeIt fulfills 3 evaluate x . evaluate y == evaluate (compose x y) numeric-preludeQC.choose (1,10) /\ \expon (QC.Positive x) xs -> let xt = x:xs in equalTrunc 15 (PS.pow (const x) (1 % expon) (PST.coeffs (PST.fromCoeffs xt ^ expon)) ++ repeat zero) (xt ++ repeat zero)  :None, numeric-preludeSince the inner series must start with a zero, the first term is omitted in y.  ;None,> numeric-preludeIn order to handle both variables equivalently we maintain a list of coefficients for terms of the same total degree. That is eval [[a], [b,c], [d,e,f]] (x,y) == a + b*x+c*y + d*x^2+e*x*y+f*y^2Although the sub-lists are always finite and thus are more like polynomials than power series, division and square root computation are easier to implement for power series.  <None,  =None,>[ numeric-prelude Laws.identity (+) zero . intPolyLaws.commutative (+) . intPolyLaws.associative (+) . intPolyLaws.identity (*) one . intPolyLaws.commutative (*) . intPolyLaws.associative (*) . intPoly'Laws.leftDistributive (*) (+) . intPoly Integral.propInverse . ratioPoly numeric-preludeHere the coefficients are vectors, for example the coefficients are real and the coefficents are real vectors. numeric-preludeHere the argument is a vector, for example the coefficients are complex numbers or square matrices and the coefficents are reals. numeric-prelude . is the functional composition of polynomials.It fulfills ' eval x . eval y == eval (compose x y) numeric-preludeThe * instance is intensionally built from the ; structure of the polynomial coefficients. If we would use  Integral.C a superclass, then the Euclidean algorithm could not determine the greatest common divisor of e.g. [1,1] and [2].  >None,s numeric-prelude$Determine mask by Gauss elimination.R - alternating binomial coefficients L - differences of translated polynomials in columnsp2 = L * R^(-1) * mR * L^(-1) * p2 = mgenAdmissibleMask /\ \(mask,poly) -> hasMultipleZero (fromMaybe 0 $ Poly.degree poly) 1 (polyFromMask (Mask.fromPolynomial poly) - polyFromMask mask)genShortPolynomial 5 /\ \poly -> maybe False (Poly.collinear poly) $ Mask.toPolynomial $ Mask.fromPolynomial poly numeric-prelude*If the mask does not sum up to a power of 1/2 then the function returns ).fmap ((6::Rational) *>) $ Mask.toPolynomial (Mask.fromCoeffs [0.1, 0.02, 0.005::Rational])Just (Polynomial.fromCoeffs [-12732 % 109375,272 % 625,-18 % 25,1 % 1]) numeric-preludegenShortPolynomial 5 /\ \poly -> poly == Mask.refinePolynomial (Mask.fromPolynomial poly) polyfmap (round :: Double -> Integer) $ fmap (1000000*) $ nest 50 (Mask.refinePolynomial (Mask.fromCoeffs [0.1, 0.02, 0.005])) (Poly.fromCoeffs [0,0,0,1])6Polynomial.fromCoeffs [-116407,435200,-720000,1000000] numeric-prelude)Convolve polynomials via refinement mask.=(mask x + ux*(-1,1)^degree x) * (mask y + uy*(-1,1)^degree y) ? (c) Henning Thielemann 2004-2005$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone,>4  @ (c) Henning Thielemann 2004-2005$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone,  numeric-preludecf. =r numeric-preludeGiven an approximation of a root, the degree of the polynomial and maximum value of coefficients, find candidates of polynomials that have approximately this root and show the actual value of the polynomial at the given root approximation.This algorithm runs easily into a stack overflow, I do not know why. We may also employ a more sophisticated integer relation algorithm, like PSLQ and friends.  ANone  numeric-preludeThe root degree must be positive. This way we can implement multiplication using only multiplication from type a. numeric-preludeexponent must be non-negative numeric-preludeexponent can be negative numeric-preludeexponent must be positive numeric-prelude When you use fmap you must assert that 8forall n. fmap f (Cons d x) == fmap f (Cons (n*d) (x^n))  B(c) Mikael Johansson 2006mik@math.uni-jena.de provisional%requires multi-parameter type classesNone,  numeric-preludeRight (left?) group action on the Integers. Close to, but not the same as the module action in Algebra.Module. numeric-preludecandidates for Utility ?  C(c) Henning Thielemann 2006$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone, numeric-preludeWe shall make a little bit of a hack here, enabling us to use additive or multiplicative syntax for groups as we wish by simply instantiating Num with both operations corresponding to the group operation of the permutation group we're studyingThere are quite a few way we could represent elements of permutation groups: the images in a row, a list of the cycles, et.c. All of these differ highly in how complex various operations end up being. numeric-prelude5Does not check whether the input values are in range. numeric-preludeThese instances may need more work They involve converting a permutation to a table.  D(c) Henning Thielemann 2007$numericprelude@henning-thielemann.de provisionalportableNone, numeric-preludeCons z (indexMapFromList [(x0,[y00,y01]), (x1,[y10]), (x2,[y20,y21,y22])])! represents the partial fraction z + y00x0 + y01 x0^2 + y10x1 + y20x2 + y21 x2^2 + y22x2^3 The denominators x0, x1, x2, ... must be irreducible, but we can't check this in general. It is also not enough to have relatively prime denominators, because when adding two partial fraction representations there might concur denominators that have non-trivial common divisors. numeric-preludeUnchecked construction. numeric-preludes`< is not really necessary here and only due to invokation of  . numeric-preludes`< is not really necessary here and only due to invokation of . numeric-preludefromFactoredFraction x y1 computes the partial fraction representation of  y % product x, where the elements of x must be irreducible. The function transforms the factors into their standard form with respect to unit factors.There are more direct methods for special cases like polynomials over rational numbers where the denominators are linear factors.'QC.listOf genSmallPrime /\ fractionConvfmap (take 3) (QC.listOf genIrreduciblePolynomial) /\ fractionConv numeric-prelude*QC.listOf genSmallPrime /\ fractionConvAltfmap (take 3) (QC.listOf genIrreduciblePolynomial) /\ fractionConvAlt numeric-preludeThe list of denominators must contain equal elements. Sorry for this hack. numeric-preludeA normalization step which separates the integer part from the leading fraction of each sub-list. numeric-preludeCf. Number.Positional numeric-preludeA normalization step which reduces all elements in sub-lists modulo their denominators. Zeros might be the result, that must be remove with  . numeric-preludeRemove trailing zeros in sub-lists because if lists are converted to fractions by   we must be sure that the denominator of the (cancelled) fraction is indeed the stored power of the irreducible denominator. Otherwise   leads to wrong results. numeric-preludeTransforms a product of two partial fractions into a sum of two fractions. The denominators must be at least relatively prime. Since   requires irreducible denominators, these are also relatively prime. Example: mulFrac (1%6) (1%4)% fails because of the common divisor 2. numeric-preludeWorks always but simply puts the product into the last fraction. numeric-preludeAlso works if the operands share a non-trivial divisor. However the results are quite arbitrary. numeric-preludeExpects an irreducible denominator as associate in standard form. numeric-prelude-genPartialFractionInt /\ \x k -> scaleInt k x.genPartialFractionPoly /\ \x k -> scaleInt k x numeric-preludegenPartialFractionInt /\ \x -> genPartialFractionInt /\ \y -> mul x ygenPartialFractionPoly /\ \x -> genPartialFractionPoly /\ \y -> mul x y numeric-preludeApply a function on a specific element if it exists, and another function to the rest of the map. numeric-preludegenPartialFractionInt /\ \x -> genPartialFractionInt /\ \y -> add x ygenPartialFractionInt /\ \x -> genPartialFractionInt /\ \y -> sub x ygenPartialFractionPoly /\ \x -> genPartialFractionPoly /\ \y -> add x ygenPartialFractionPoly /\ \x -> genPartialFractionPoly /\ \y -> sub x y  E2(c) Henning Thielemann 2009, Mikael Johansson 2006$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone,>'l numeric-prelude8A matrix is a twodimensional array, indexed by integers. numeric-preludeTransposition of matrices is just transposition in the sense of Data.List.genIntMatrix /\ \a -> Matrix.rows a == Matrix.columns (Matrix.transpose a)genIntMatrix /\ \a -> Matrix.columns a == Matrix.rows (Matrix.transpose a)genIntMatrix /\ \a -> genSameMatrix a /\ \b -> Laws.homomorphism Matrix.transpose (+) (+) a b numeric-preludegenIntMatrix /\ \a -> a == uncurry Matrix.fromRows (Matrix.dimension a) (Matrix.rows a) numeric-preludegenIntMatrix /\ \a -> a == uncurry Matrix.fromColumns (Matrix.dimension a) (Matrix.columns a) numeric-preludegenIntMatrix /\ \a -> Laws.identity (+) (uncurry Matrix.zero $ Matrix.dimension a) a numeric-preludegenDimension /\ \n -> Matrix.one n == Matrix.diagonal (replicate n Ring.one :: [Integer]) numeric-preludegenIntMatrix /\ \a -> Laws.leftIdentity (*) (Matrix.one (Matrix.numRows a)) agenIntMatrix /\ \a -> Laws.rightIdentity (*) (Matrix.one (Matrix.numColumns a)) agenIntMatrix /\ \a -> genFactorMatrix a /\ \b -> Laws.homomorphism Matrix.transpose (*) (flip (*)) a bgenIntMatrix /\ \a -> genFactorMatrix a /\ \b -> genFactorMatrix b /\ \c -> Laws.associative (*) a b cgenIntMatrix /\ \b -> genSameMatrix b /\ \c -> genFactorMatrix b /\ \a -> Laws.leftDistributive (*) (+) a b cgenIntMatrix /\ \a -> genFactorMatrix a /\ \b -> genSameMatrix b /\ \c -> Laws.rightDistributive (*) (+) a b cQC.choose (0,10) /\ \k -> genDimension /\ \n -> genMatrixFor n n /\ \a -> a^k == nest (fromInteger k) ((a::Matrix.T Integer)*) (Matrix.one n) numeric-preludegenIntMatrix /\ \a -> genSameMatrix a /\ \b -> Laws.commutative (+) a bgenIntMatrix /\ \a -> genSameMatrix a /\ \b -> genSameMatrix b /\ \c -> Laws.associative (+) a b c  FNone,>'  GNone,>)0 numeric-preludeA value of type   stores information on how to resolve unit violations. The main application of the module are certainly Number.Physical type instances but in principle it can also be applied to other occasionally scalar types.   HNone>)( (  7 7 7INone,>, numeric-prelude3The super class is only needed to state the laws  v == zero == norm v == zero norm (scale x v) == abs x * norm v norm (u+v) <= norm u + norm v numeric-preludeDefault definition for   that is based on  class. numeric-preludeDefault definition for   that is based on : class and the argument vector has at least one component.  JNone,>-. numeric-preludeDefault definition for   that is based on  class. numeric-preludeDefault definition for   that is based on : class and the argument vector has at least one component.  KNone,>/ numeric-prelude8 numeric-preludeWe like to build the Complex Algebraic instance on top of the Algebraic instance of the scalar type. This poses no problem to . However, Lt requires computing the complex argument which is a transcendent operation. In order to keep the type class dependencies clean for more sophisticated algebraic number types, we introduce a type class which actually performs the radix operation. numeric-prelude&Complex numbers are an algebraic type. numeric-prelude real part numeric-preludeimaginary part numeric-prelude8Construct a complex number from real and imaginary part. numeric-prelude7Construct a complex number with negated imaginary part. numeric-prelude"The conjugate of a complex number. numeric-prelude(Scale a complex number by a real number. numeric-preludeExponential of a complex number with minimal type class constraints. numeric-prelude(Turn the point one quarter to the right. numeric-prelude(Turn the point one quarter to the right. numeric-prelude&Scale a complex number to magnitude 1.For a complex number z,  z# is a number with the magnitude of z7, but oriented in the positive real direction, whereas   z has the phase of z, but unit magnitude. numeric-preludeForm a complex number from polar components of magnitude and phase. numeric-prelude  t# is a complex value with magnitude 1 and phase t (modulo 2*). numeric-prelude,The phase of a complex number, in the range (-, ]2. If the magnitude is zero, then so is the phase. numeric-prelude The function   takes a complex number and returns a (magnitude, phase) pair in canonical form: the magnitude is nonnegative, and the phase in the range (-, ]1; if the magnitude is zero, then so is the phase. numeric-preludeThe  method can't replace  5 because it requires the Algebra.Module constraint  6 6M$numericprelude@henning-thielemann.de provisional portable (?)None,>Anumeric-preludeQuaternions could be defined based on Complex numbers. However quaternions are often considered as real part and three imaginary parts.numeric-prelude real partnumeric-preludeimaginary partsnumeric-prelude4Construct a quaternion from real and imaginary part.numeric-preludeThe conjugate of a quaternion.numeric-prelude$Scale a quaternion by a real number.numeric-preludethe same as NormedEuc.normSqr but with a simpler type class constraintnumeric-prelude)scale a quaternion into a unit quaternionnumeric-prelude4similarity mapping as needed for rotating 3D vectors It holds similarity (cos(a/2) +:: scaleImag (sin(a/2)) v) (0 +:: x) == (0 +:: y) where y results from rotating x around the axis v by the angle a.numeric-preludeLet c% be a unit quaternion, then it holds .similarity c (0+::x) == toRotationMatrix c * xnumeric-preludeThe rotation matrix must be normalized. (I.e. no rotation with scaling) The computed quaternion is not normalized.numeric-preludeMap a quaternion to complex valued 2x2 matrix, such that quaternion addition and multiplication is mapped to matrix addition and multiplication. The determinant of the matrix equals the squared quaternion norm (). Since complex numbers can be turned into real (orthogonal) matrices, a quaternion could also be converted into a real matrix.numeric-preludeRevert .numeric-preludeSpherical Linear InterpolationCan be generalized to any transcendent Hilbert space. In fact, we should also include the real part in the interpolation.numeric-preludeThe  method can't replace 5 because it requires the Algebra.Module constraintnumeric-preludeFor 0 return vector v, for 1 return vector w numeric-preludevector v, must be normalized numeric-preludevector w, must be normalized 66N (c) Henning Thielemann 2004-2006$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone,>Inumeric-prelude(Polynomial including negative exponents numeric-preludeAdd lists of numbers respecting a relative shift between the starts of the lists. The shifts must be non-negative. The list of relative shifts is one element shorter than the list of summands. Infinitely many summands are permitted, provided that runs of zero shifts are all finite.#We could add the lists either with W or with X, W would be straightforward, but more time consuming (quadratic time) whereas foldr is not so obvious but needs only linear time.(stars denote the coefficients, frames denote what is contained in the interim results) W sums this way: | | | ******************************* | | +-------------------------------- | | ************************ | +---------------------------------- | ************ +------------------------------------I.e. W would use much time find the time differences by successive subtraction 1.X mixes this way:  +-------------------------------- | ******************************* | +------------------------- | | ************************ | | +------------- | | | ************numeric-preludeTwo polynomials may be stored differently. This function checks whether two values of type LaurentPolynomial( actually represent the same polynomial.numeric-preludeCheck whether a Laurent polynomial has only the absolute term, that is, it represents the constant polynomial.numeric-preludep(z) -> p(-z) numeric-preludep(z) -> p(1/z) numeric-prelude%p(exp(ix)) -> conjugate(p(exp(ix)))If you interpret (p*) as a linear operator on the space of Laurent polynomials, then  (adjoint p *) is the adjoint operator.ONone,s-numeric-preludeConverts all digits to non-negative digits, that is the usual positional representation. However the conversion will fail when the remaining digits are all zero. (This cannot be improved!)numeric-preludeRequires, that no digit is  (basis-1) or  (1-basis)3. The leading digit might be negative and might be -basis or basis.numeric-preludeMay prepend a digit.numeric-prelude*Compress first digit. May prepend a digit.numeric-preludeDoes not prepend a digit.numeric-preludeCompress second digit. Sometimes this is enough to keep the digits in the admissible range. Does not prepend a digit.numeric-prelude7Eliminate leading zero digits. This will fail for zero.numeric-prelude9Trim until a minimum exponent is reached. Safe for zeros.numeric-preludeAccept a high leading digit for the sake of a reduced exponent. This eliminates one leading digit. Like  but with exponent management.numeric-prelude>Merge leading and second digit. This is somehow an inverse of .numeric-preludeMake sure that a number with absolute value less than 1 has a (small) negative exponent. Also works with zero because it chooses an heuristic exponent for stopping.numeric-prelude'Split into integer and fractional part.numeric-preludecf. uvnumeric-preludeOnly return as much digits as are contained in Double. This will speedup further computations.numeric-prelude$Show a number with respect to basis 10^e.numeric-preludeConvert from a b basis representation to a b^e basis.Works well with every exponent.numeric-preludeConvert from a b^e basis representation to a b basis.Works well with every exponent.numeric-preludeConvert between arbitrary bases. This conversion is expensive (quadratic time).numeric-preludeThe basis must be at least ***. Note: Equality cannot be asserted in finite time on infinite precise numbers. If you want to assert, that a number is below a certain threshold, you should not call this routine directly, because it will fail on equality. Better round the numbers before comparison.numeric-prelude3If all values are completely defined, then it holds "if b then x else y == ifLazy b x y However if b is undefined, then it is at least known that the result is between x and y.numeric-prelude mean2 b (x0,x1) (y0,y1) computes  round ((x0.x1 + y0.y1)/2) , where x0.x1 and y0.y17 are positional rational numbers with respect to basis bnumeric-preludeGet the mantissa in such a form that it fits an expected exponent.x and (e, alignMant b e x) represent the same number.numeric-prelude3Add two numbers but do not eliminate leading zeros.numeric-prelude Add at most basis> summands. More summands will violate the allowed digit range.numeric-preludeAdd many numbers efficiently by computing sums of sub lists with only little carry propagation.numeric-preludeAdd an infinite number of numbers. You must provide a list of estimate of the current remainders. The estimates must be given as exponents of the remainder. If such an exponent is too small, the summation will be aborted. If exponents are too big, computation will become inefficient.numeric-preludeLike {, but it pads with zeros if the list is too short. This way it preserves ) length (fst (splitAtPadZero n xs)) == n numeric-preludehelp showing series summandsnumeric-preludeFor obtaining n result digits it is mathematically sufficient to know the first (n+1) digits of the operands. However this implementation needs (n+2) digits, because of calls to  in both  and . We should fix that.numeric-preludeUndefined if the divisor is zero - of course. Because it is impossible to assert that a real is zero, the routine will not throw an error in general.ToDo: Rigorously derive the minimal required magnitude of the leading divisor digit.numeric-preludeFast division for small integral divisors, which occur for instance in summands of power series.numeric-prelude Square root.We need a leading digit of type Integer, because we have to collect up to 4 digits. This presentation can also be considered as .ToDo: Rigorously derive the minimal required magnitude of the leading digit of the root.Mathematically the n>th digit of the square root depends roughly only on the first n& digits of the input. This is because  sqrt (1+eps)  1 + eps/2'. However this implementation requires 2*n input digits for emitting n, digits. This is due to the repeated use of 0. It would suffice to fully compress only every basisth iteration (digit) and compress only the second leading digit in each iteration.9Can the involved operations be made lazy enough to solve y = (x+frac)^2 by frac = (y-x^2-frac^2) / (2*x) ?numeric-preludeNewton iteration doubles the number of correct digits in every step. Thus we process the data in chunks of sizes of powers of two. This way we get fastest computation possible with Newton but also more dependencies on input than necessary. The question arises whether this implementation still fits the needs of computational reals. The input is requested as larger and larger chunks, and the input itself might be computed this way, e.g. a repeated square root. Requesting one digit too much, requires the double amount of work for the input computation, which in turn multiplies time consumption by a factor of four, and so on.Optimal fast implementation of one routine does not preserve fast computation of composed computations.8The routine assumes, that the integer parts is at least b^2.numeric-preludeList.inits is defined by -inits = foldr (x ys -> [] : map (x:) ys) [[]]'This is too strict for our application. Prelude> List.inits (0:1:2:undefined) [[],[0],[0,1]*** Exception: Prelude.undefined(The following routine is more lazy than  and even lazier than wx from  utility-ht package, but it is restricted to infinite lists. This degree of laziness is needed for sqrtFP. Prelude> lazyInits (0:1:2:undefined) [[],[0],[0,1],[0,1,2],[0,1,2,*** Exception: Prelude.undefinednumeric-prelude-Absolute value of argument should be below 1.numeric-preludeResidue estimates will only hold for exponents with absolute value below one.The computation is based on ", thus the denominator should not be too big. (Say, at most 1000 for 1000000 digits.)It is not optimal to split the power into pure root and pure power (that means, with integer exponents). The root series can nicely handle all exponents, but for exponents above 1 the series summands rises at the beginning and thus make the residue estimate complicated. For powers with integer exponents the root series turns into the binomial formula, which is just a complicated way to compute a power which can also be determined by simple multiplication.numeric-prelude-Absolute value of argument should be below 1.numeric-prelude-Absolute value of argument should be below 1.numeric-preludeLike  but converges faster. It calls  cosSinSmall; with reduced arguments using the trigonometric identities  cos (4*x) = 8 * cos x ^ 2 * (cos x ^ 2 - 1) + 1 sin (4*x) = 4 * sin x * cos x * (1 - 2 * sin x ^ 2) ;Note that the faster convergence is hidden by the overhead.The same could be achieved with a fourth power of a complex number.numeric-prelude 9x' = x - (exp x - y) / exp x = x + (y * exp (-x) - 1) First, the dependencies on low-significant places are currently much more than mathematically necessary. Check  *Number.Positional> expSmall 1000 (-1,100 : replicate 16 0 ++ [undefined]) (0,[1,105,171,-82,76*** Exception: Prelude.undefined 3 Every multiplication cut off two trailing digits.  *Number.Positional> nest 8 (mul 1000 (-1,repeat 1)) (-1,100 : replicate 16 0 ++ [undefined]) (-9,[101,*** Exception: Prelude.undefined Possibly the dependencies of expSmall could be resolved by not computing mul immediately but computing mul series which are merged and subsequently added. But this would lead to an explosion of series.Second, even if the dependencies of all atomic operations are reduced to a minimum, the mathematical dependencies of the whole iteration function are less than the sums of the parts. Lets demonstrate this with the square root iteration. It is  (1.4140 + 21.4140) # 2 == 1.414213578500707 (1.4149 + 21.4149)  2 == 1.4142137288854335  That is, the digits 213! do not depend mathematically on x of 1.414x, but their computation depends. Maybe there is a glorious trick to reduce the computational dependencies to the mathematical ones.numeric-preludeThis is an inverse of , also known as atan2 with flipped arguments. It's very slow because of the computation of sinus and cosinus. However, because it uses the  implementation as estimator, the final application of arctan series should converge rapidly.It could be certainly accelerated by not using cosSin and its fiddling with pi. Instead we could analyse quadrants before calling atan2, then calling cosSinSmall immediately.numeric-prelude9Arcus tangens of arguments with absolute value less than  1 / sqrt 3.numeric-preludeEfficient computation of Arcus tangens of an argument of the form 1/n.numeric-preludeThis implementation gets the first decimal place for free by calling the arcus tangens implementation for  s.numeric-prelude"A classic implementation without ' cheating'% with floating point implementations.For x < 1 / sqrt 3 (1 / sqrt 3 == tan (pi/6)) use arctan power series. (sqrt 3 is approximately 19/11.)For  x > sqrt 3 use arctan x = pi/2 - arctan (1/x) For other x use*arctan x = pi/4 - 0.5*arctan ((1-x^2)/2*x) (which follows from /arctan x + arctan y == arctan ((x+y) / (1-x*y))3 which in turn follows from complex multiplication !(1:+x)*(1:+y) == ((1-x*y):+(x+y))If x is close to sqrt 3 or  1 / sqrt 3& the computation is quite inefficient.PNone,zYnumeric-prelude The value  Cons b e m represents the number .b^e * (m!!0 / 1 + m!!1 / b + m!!2 / b^2 + ...)5. The interpretation of exponent is chosen such that #floor (logBase b (Cons b e m)) == e. That is, it is good for multiplication and logarithms. (Because of the necessity to normalize the multiplication result, the alternative interpretation wouldn't be more complicated.) However for base conversions, roots, conversion to fixed point and working with the fractional part the interpretation 0b^e * (m!!0 / b + m!!1 / b^2 + m!!2 / b^3 + ...)9 would fit better. The digits in the mantissa range from 1-base to base-1. The representation is not unique and cannot be made unique in finite time. This way we avoid infinite carry ripples.numeric-preludeShift digits towards zero by partial application of carries. E.g. 1.8 is converted to 2.(-2) If the digits are in the range (1-base, base-1)' the resulting digits are in the range  ((1-base) 2-2, (base-1)2+2). The result is still not unique, but may be useful for further processing.numeric-prelude7perfect carry resolution, works only on finite numbers QNone|numeric-preludeThis makes a type usable with Haskell98 type classes that was initially implemented for NumericPrelude typeclasses. E.g. if a is in class , then T a is both in class  and in .&You can even lift container types. If  Polynomial a is in  for all types a that are in , then .T (Polynomial (MathObj.Wrapper.Haskell98.T a)) is in  for all types a that are in .RNone,>}numeric-prelude$Remove all zero values from the map.SNone,numeric-preludeA Unit.T is a sparse vector with integer entries Each map n->m means that the unit of the n-th dimension is given m times.Example: Let the quantity of length (meter, m) be the zeroth dimension and let the quantity of time (second, s) be the first dimension, then the composed unit m/s^2 corresponds to the Map [(0,1),(1,-2)].In future I want to have more abstraction here, e.g. a type class from the Edison project that abstracts from the underlying implementation. Then one can easily switch between Arrays, Binary trees (like Map) and what know I.numeric-preludeThe neutral Unit.Tnumeric-preludeTest for the neutral Unit.Tnumeric-preludeConvert a List to sparse Map representation Example: [-1,0,-2] -> [(0,-1),(2,-2)]numeric-preludeConvert Map to a ListTNone,numeric-preludeA common scaling for a unit.numeric-prelude'An entry for a unit and there scalings.numeric-prelude,If True the symbols must be preceded with a . Though it sounds like an attribute of Scale it must be the same for all scales and we need it to sort positive powered unitsets to the front of the list of unit components. numeric-preludeRaise all scales of a unit and the unit itself to the n-th power numeric-preludeReorder the unit components in a way that the units with positive exponents lead the list. numeric-prelude)Decompose a complex unit into common onesnumeric-preludeFind the exponent that lead to minimal distance Since the list is infinite Q will fail but the sequence is convex and thus we can abort when the distance stop fallingnumeric-prelude;(UnitSet,distance) the UnitSet may contain powered units **UNone,numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeSome common quantity classes.numeric-preludeCommon constantsnumeric-preludeConversion factorsnumeric-preludePhysical constantsnumeric-preludePrefixes used for SI unitsnumeric-prelude2UnitDatabase.T of units and their common scalings numeric-prelude2UnitDatabase.T of units and their common scalings VNone,((WNone,>numeric-preludeA Physics.Quantity.Value.T combines a numeric value with a physical unit.numeric-preludeConstruct a physical value from a numeric value and the full vector representation of a unit.numeric-prelude4Test for the neutral Unit.T. Also a zero has a unit!numeric-prelude?apply a function to the numeric value while preserving the unitnumeric-prelude;Add two values if the units match, otherwise return Nothingnumeric-preludeSubtract two values if the units match, otherwise return NothingXNone,7numeric-preludeShow the physical quantity in a human readable form with respect to a given unit data base. numeric-preludeReturns the rescaled value as number and the unit as string. The value can be used re-scale connected values and display them under the label of the unit numeric-preludeChoose a scale where the number becomes handy and return the scaled number and the corresponding scale. numeric-preludeunused numeric-preludeunused  YNone,numeric-preludeThis function could also return the value, but a list of pairs (String, Integer) is easier for testing. ZNone,>H//[None,"  55yNone} 43ghfe 2cbnopRPQVUTWXS65(+ !"#$*)%0./&',-1789:;<=>?@ABCDEFGHIJKLMNOYZ[\]^_`adijklmqrstuvwxyz{|}~ !"# 43ghfe 2cbnopRPQVUTWXS65(+$*)%0./&',-1789:;<=>?@ABCDEFGHIJKLMNOYZ[\]^_`adijklmqrstuvwxyz{|}~zNone><numeric-preludeA special reader monad.numeric-preludeThe type class is for representing affine spaces via affine combinations. However, we didn't find a way to both ensure the property that the combination coefficients sum up to 1, and keep it efficient.We propose this class instead of a combination of Additive and Module for interpolation for those types, where scaling and addition alone makes no sense. Such types are e.g. internal filter parameters in signal processing: For these types interpolation makes definitely sense, but addition and scaling make not.That is, both classes are isomorphic (you can define one in terms of the other), but instances of this class are more easily defined, and using an AffineSpace constraint instead of Module in a type signature is important for documentation purposes. AffineSpace should be superclass of Module. (But then you may ask, why not adding another superclass for Convex spaces. This class would provide a linear combination operation, where the coefficients sum up to one and all of them are non-negative.)We may add a safety layer that ensures that the coefficients sum up to 1, using start points on the simplex and functions to move on the simplex. Start points have components that sum up to 1, e.g. (1, 0, 0, 0) (0, 1, 0, 0) (0, 0, 1, 0) (0, 0, 0, 1) (1/4, 1/4, 1/4, 1/4)5Then you may move along the simplex in the directions /(1, -1, 0, 0) (0, 1, 0, -1) (-1, -1, 3, -1)7which are characterized by components that sum up to 0.,For example linear combination is defined by lerp k (a,b) = (1-k)*>a + k*>bthat is the coefficients are (1-k) and k. The pair (1-k, k) can be constructed by starting at pair (1,0) and moving k units in direction (-1,1). (1-k, k) = (1,0) + k*(-1,1)It is however a challenge to manage the coefficient tuples in a type safe and efficient way. For small numbers of interpolation nodes (constant, linear, cubic interpolation) a type level list would appropriate, but what to do for large tuples like for Whittaker interpolation?As side note: In principle it would be sufficient to provide an affine combination of two points, since all affine combinations of more points can be decomposed into such simple combinations. lerp a x y = (1-a)*>x + a*>yE.g. a*>x + b*>y + c*>z with a+b+c=1 can be written as lerp c (lerp (b/(1-c)) x y) z. More generally you can use lerpnorm a b x y = lerp (b/(a+b)) x y = (a/(a+b))*>x + (b/(a+b))*>y for writing >a*>x + b*>y + c*>z == lerpnorm (a+b) c (lerpnorm a b x y) zor a*>x + b*>y + c*>z + d*>w == lerpnorm (a+b+c) d (lerpnorm (a+b) c (lerpnorm a b x y) z) wwith  a+b+c+d=1.The downside is, that lerpnorm requires division, that is, a field, whereas the computation of the coefficients sometimes only requires ring operations.numeric-preludeInfix variant of . 6{|}~{{{{{{|{|{|{{{{~~{|{|{|{|{{{{~{|{|~{{~~~~~{~~{~{{~{{~~~{|~{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{i{{{{{{{{{{{{{{{{{{{{{{{{{{{|{|{|{|{|{|{|{|{|{j{~~~~~~~~~```            `                                       `                   `                                   `           ``i``h````````b``` `            !`!!t!!!!!!!!!"`"""""q"""""""""""""""""""""""""""""""""""#`#d############################################$`$$$%`%%%&`&&&&&&&&&&&&&&&'''''''''''''''''''''''''''''''''''''''(((((i))))))))))*******++++++++++++++++++++++,,,,,,,,,,,,,,---------------------....................../////////////////////////////////////////////////////////////0000000000000111111111111111111111111111111122222{222222222223333333333333333333333333r333444444444444444444444444444444444444444455555555555555555555555555555555555555555556666666666666666t6666666666666677777777777777777777777777777777888888999999999999999999999999999999999::::::::::::::::::;;;;;;;;;;;;;;;;;;;;;;;<<<<<<<<<<<<<<<<<<==================================>>>>>>>>>>>>????????????????????t?????????@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@AAAAAAAAhAAAAAtAAAAABBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDiDDDDDDDDDDDDDDDDEEEEEEEEEEEEEEiEEEEEEEEEEEEEEEF`FFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHI`IIIIIIIIIIIIJ`JJJJJJJJJJJJK`KKKKKKKKKKKKKKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLcLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMM M M M M M M M MMMMMMMMMMMMNNN NNN NN NN N NNNNN N N NNNNhN N N N NNN NNNNNNNNNO O O O O O OO O O O O O O O O O O O O O O O O O O O O O O O O O OO O O O O O O O O O O O O O O O O O O OO O O O O O O O O O OOOO O O O O O O OO O O OOO O O O O O OO O O O O O O OO O OO O O O OOtO O O O OO O OO O OOO OO OO OOO OOOO PPP{PP P P P PPPP P P P P P PPPP PPPPPPPPPPPPPPPQQQQQQQQ Q QQ Q Q Q QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ R R R R R R R R R SSS S S S S S T T T TcT T T T T T T T T T T T T T T T T T TT T T T T T T T T T T T T T T T T T T T T UUUUUUUUUU U U UUU U UU U U UUU UU U UU UUU U U U U U U U U U U U U U U U U U U U U U U U U U U U U U U U U U U U UU U U U U U U U U U U U U U U U U V V V V V V V V V V V V V V V V V V V WWW W W WWW W W W W WW W W WWWWWWWWWWWWWWWWWX X X X X X X X X X Y Y Y Y Y Y Y Y Z ZZZZZ Z ZZ Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z ZZZZZZZZZZZZZZZZZZ[`[ [ [ [ [ [ [ [ [[[[[ [[\\\ \ \]`] ] ]] ^`^^ ^ ^ ^ ^^^^^ ^ ^ ^^ ^ ^ ^ _ _ _ _ _ _ {  { LM{xz z`z z z z zzz zz z z ,numeric-prelude-0.4.4-8ccUpT2Pvo7LJs1GUJp3wzNumericPrelude.BaseNumericPrelude.NumericNumber.NonNegativeAlgebra.DimensionTermAlgebra.Indexable Algebra.LawsMathObj.PermutationMathObj.Permutation.TableNumericPrelude.ElementwiseAlgebra.AdditiveAlgebra.ZeroTestable Algebra.RingAlgebra.VectorAlgebra.RightModuleAlgebra.MonoidMathObj.AlgebraAlgebra.NonNegativeAlgebra.IntegralDomain Algebra.UnitsAlgebra.PrincipalIdealDomainMathObj.MonoidAlgebra.DifferentialAlgebra.Absolute Number.Ratio Algebra.FieldAlgebra.ToRationalAlgebra.RealIntegralAlgebra.ToIntegerAlgebra.ModuleAlgebra.VectorSpaceAlgebra.DivisibleSpaceAlgebra.ModuleBasisAlgebra.AlgebraicAlgebra.TranscendentalAlgebra.RealRingAlgebra.RealFieldAlgebra.RealTranscendentalAlgebra.FloatingPointMathObj.Wrapper.Haskell98NumericPrelude.List.CheckedNumericPrelude.List.GenericNumber.ResidueClassNumber.ResidueClass.ReaderNumber.ResidueClass.MaybeNumber.ResidueClass.FuncNumber.ResidueClass.Check Number.PeanoNumber.PartiallyTranscendentalNumber.NonNegativeChunkyNumber.GaloisField2p32m5MathObj.Polynomial.CoreMathObj.PowerSeries.CoreMathObj.PowerSeries.ExampleNumber.FixedPointNumber.FixedPoint.Check(MathObj.PowerSeries.DifferentialEquationMathObj.PowerSeriesMathObj.PowerSeries2.CoreMathObj.PowerSeries2MathObj.PowerSeries.MeanMathObj.PolynomialMathObj.RefinementMask2MathObj.PowerSumMathObj.RootSet Number.RootMathObj.Permutation.CycleList#MathObj.Permutation.CycleList.CheckMathObj.PartialFractionMathObj.MatrixAlgebra.OccasionallyScalar#Number.OccasionallyScalarExpressionNumber.DimensionTermAlgebra.NormedSpace.SumAlgebra.NormedSpace.MaximumAlgebra.NormedSpace.EuclideanNumber.ComplexNumber.QuaternionMathObj.LaurentPolynomialNumber.PositionalNumber.Positional.CheckMathObj.Wrapper.NumericPreludeMathObj.DiscreteMapNumber.Physical.UnitNumber.Physical.UnitDatabaseNumber.SI.UnitNumber.DimensionTerm.SINumber.PhysicalNumber.Physical.ShowNumber.Physical.Read Number.SIAlgebra.LatticeAlgebra.RealRing98Algebra.EqualityDecisionAlgebra.OrderDecisionNumericPrelude.ListC Algebra.Core ringPower magnitude splitFractionAlgebraTranscendentalPreludedivzipWith undefinedproperFraction RealFloatControl.Monad.STrunSTNumeric.NonNegativeChunky**mulLinearFactorPrincipalIdealDomainrootNumeric floatToDigits Data.List.HTinitsNumericPreludeAlgebra.AffineSpacebaseGHC.Base++ghc-primGHC.PrimseqGHC.Listfilterzip System.IOprint Data.Tuplefstsnd otherwisemap$GHC.EnumenumFrom enumFromThen enumFromToenumFromThenTo GHC.Classes==>=>>=>>fmapreturnControl.Monad.FailfailGHC.Real realToFracBoundedEnumEqMonadFunctorOrdGHC.ReadReadGHC.ShowShow GHC.TypesBoolCharDoubleFloatIntinteger-wired-inGHC.Integer.TypeInteger GHC.MaybeMaybeOrderingIO Data.EitherEitherFalseNothingJustTrueLeftRightLTEQGTString/=maxBoundminBoundData.TraversablesequencemapMreadIOreadLn appendFile writeFilereadFileinteract getContentsgetLinegetCharputStrLnputStrputCharGHC.IO.ExceptionioErrorGHC.IOFilePath userErrorIOError Data.FoldablenotElemallanyorand concatMapconcat sequence_mapM_minimummaximumelemlengthnullfoldl1foldr1foldlfoldr Data.OldListunwordswordsunlineslines Text.Readreadreadseitherlex readParenreadList readsPrecText.ParserCombinators.ReadPReadSfromEnumtoEnumpredsucc showParen showStringshowCharshowsShowSshowListshow showsPrecunzip3unzipzipWith3zip3!!lookupreversebreakspansplitAtdroptake dropWhile takeWhilecycle replicaterepeatiteratescanr1scanrscanl1scanlinitlasttailhead Data.MaybemaybeuncurrycurryasTypeOfuntil$!flip.constid=<<<$GHC.Errerrorcompare<<=>maxmin&&||not(non-negative-0.1.2-m3H0pqzLRcGZk4oQOX07QNumeric.NonNegative.WrappertoNumberfromNumberUnsafeT(utility-ht-0.0.16-CBXUHdghqe0D7qWmL1hI1tData.Bool.HT.Private ifThenElseVoltageAnalyticalVoltage Frequency Information TemperatureAngleChargeMassTimeLengthIsScalartoScalar fromScalarSqrRecipMulScalarnoValueappPrecscalarmulrecip%*%%/% applyLeftMul applyRightMul applyRecipcommute associateLeftassociateRightrecipMulmulRecip identityLeft identityRight cancelLeft cancelRight invertRecip doubleRecip recipScalartimemasschargeangle temperature information frequencyvoltage unpackVoltage packVoltage $fCScalar $fShowScalar$fCMul $fShowMul$fCRecip $fShowRecip$fIsScalarScalar $fCLength $fShowLength$fCTime $fShowTime$fCMass $fShowMass $fCCharge $fShowCharge$fCAngle $fShowAngle$fCTemperature$fShowTemperature$fCInformation$fShowInformation $fCVoltage $fShowVoltageToOrdfromOrd ordCompare liftComparetoOrd $fCInteger$fC[]$fC(,) $fOrdToOrd $fEqToOrd $fShowToOrd commutative associative leftIdentity rightIdentityidentityleftZero rightZerozero leftInverse rightInverseinverseleftDistributiverightDistributive homomorphism rightCascade leftCascadedomainapplycatch fromFunction toFunctionfromPermutation fromCyclescomposechooseclosure closureSlowConsrunwithelementrun2run3run4run5$fApplicativeT $fFunctorT+-negatesubtractsumsum1sumNestedAssociativesumNestedCommutative elementAdd elementSub elementNeg<*>.+<*>.-<*>.-$propCommutativepropAssociative propIdentity propInverse $fCComplex$fCRatio$fC->$fC(,,) $fCWord64 $fCWord32 $fCWord16$fCWord8$fCWord$fCInt64$fCInt32$fCInt16$fCInt8$fCInt $fCDouble$fCFloatisZero defltIsZero*one fromInteger^sqrproductproduct1 scalarProductpropLeftDistributivepropRightDistributivepropLeftIdentitypropRightIdentitypropPowerCascadepropPowerProductpropPowerDistributiveeq<+>*> functorScale linearComb propCascade$fEq[]<*idt<*>cumulate$fCSum $fCProduct$fCLast$fCFirst$fCEndo$fCDual$fCAny$fCAll mulMonomialmonomial$fShowT$fCT$fCT0$fCT1$fEqTsplit splitDefaultadd-|moddivModdividessameResidueClassdecomposeVarPositionaldecomposeVarPositionalInf divCheckedsafeDiv divModZeroevenodd roundDownroundUpdivUppropMultipleDivpropMultipleModpropProjectAdditionpropProjectMultiplicationpropUniqueRepresentativepropZeroRepresentativepropSameResidueClassisUnit stdAssociatestdUnit stdUnitInvintQuery intAssociate intStandardintStandardInversepropCompositionpropInverseUnitpropUniqueAssociatepropAssociateProduct extendedGCDgcdlcmcoprimeeuclidextendedEuclidextendedGCDMulti diophantinediophantineMindiophantineMultichineseRemainderchineseRemainderMultipropMaximalDivisorpropGCDDiophantinepropExtendedGCDMultipropDiophantinepropDiophantineMinpropDiophantineMultipropDiophantineMultiMinpropDivisibleGCDpropDivisibleLCMpropGCDIdentitypropGCDCommutativepropGCDAssociativepropGCDHomogeneous propGCD_LCMpropChineseRemainderMaxrunMaxMinrunMinLCMrunLCMGCDrunGCD$fCGCD$fCLCM$fCMin$fCMax $fShowMax$fEqMax $fShowMin$fEqMin $fShowLCM$fEqLCM $fShowGCD$fEqGCD differentiateabssignumabsOrd signumOrdRational:% numerator denominator fromValuescale% showsPrecAuto toRational98 $fFractionalT$fNumT $fRandomT $fStorableT $fArbitraryT$fReadT$fOrdT$fCT2$fCT3/ fromRational'^- fromRational propDivisionpropReciprocal toRational realToFieldquotremquotRem toInteger fromIntegral fieldPower<*>.*>integerMultiply $fCaComplex$fCa->$fCa[]$fCa(,,)$fCa(,) $fCIntegerT$fCTT$fCIntegerInteger $fCInt64Int64 $fCInt32Int32 $fCInt16Int16 $fCInt8Int8 $fCIntInt$fCDoubleDouble $fCFloatFloatbasisflatten dimension propFlatten propDimensionsqrt^/ genericRootpower propSqrSqrtpiexploglogBasesincostanasinacosatansinhcoshtanhasinhacoshatanh^? propExpLog propLogExp propExpNeg propLogRecippropExpProductpropExpLogPower propLogSumpropTrigonometricPythagoras propSinPeriod propCosPeriod propTanPeriodpropSinAngleSumpropCosAngleSumpropSinDoubleAnglepropCosDoubleAngle propSinSquare propCosSquarefractionceilingfloortruncateround roundSimplefastSplitFractionfixSplitFraction fixFractionsplitFractionIntfloorInt ceilingIntroundIntroundSimpleIntapproxRational powersOfTwopairsOfPowersOfTwo genericFloorgenericCeilinggenericTruncate genericRoundgenericFractiongenericSplitFractiongenericPosFloorgenericPosCeilinggenericHalfPosFloorDigitsgenericPosRoundgenericPosFractiongenericPosSplitFractiondecisionPosFractiondecisionPosFractionSqrTimeatan2radixdigitsrangedecodeencodeexponent significandisNaN isInfiniteisDenormalizedisNegativeZeroisIEEEdeconslift1lift2unliftF1unliftF2 unimplemented$fCT4$fCT5$fCT6$fCT7$fCT8$fCT9$fCT10$fCT11$fCT12$fCT13$fCT14$fCT15$fIxT $fBoundedT$fEnumT $fIntegralT $fFloatingT$fRealT $fRealFracT $fRealFloatT lengthLeft lengthRight elemIndex elemIndices findIndex findIndicessubneg divideMaybedividetoFuncconcretefromRepresentativegetZerogetOnegetAddgetSubgetNeggetAdditiveVarsgetMul getRingVars getDividegetRecip getFieldVars monadExample runExample$fMonadTmodulusrepresentative/: matchMaybeisCompatibleMaybe isCompatiblelift0equalnotImplementedlift98_1lift98_2 factorPrecmaybeCompatible errIncompatValuablecostsvalueZeroSuccinfinityerrsubNeg fromPosEnum toPosEnumifLazy argMinFullargMin argMinimum argMaxFullargMax argMaximumisAscendingFiniteListisAscendingFiniteNumbers toListMaybeglue isAscending increaseCosts&&~andWleW isAscendingW$fShowValuable $fEqValuable $fOrdValuabletoValue fromChunkstoChunks fromChunky98 toChunky98 fromNumber normalizeisNull isPositive minMaxDiff divModLazy divModStrict $fMonoidT $fSemigroupTRatio fromNumberMsgfromNumberClip lift2IntegerhornerhornerCoeffVectorhornerArgVectorshiftunShift collinear tensorProducttensorProductAltmulShearmulShearTranspose divModRev progression integrate integrateInt alternateshrinkdilateevaluateevaluateCoeffVectorevaluateArgVector approximateapproximateCoeffVectorapproximateArgVectorholes2holes2alternate insertHoles stripLeadZerodivideStripZerorecipProgressionpowsinCos sinCosScalar derivedLog composeTaylorinvinvDiff recipExplexpExplsinExplcosExpltanExpl tanExplSievelogExplatanExplsinhExplcoshExpl atanhExplpowExplsqrtExplerfexpODEsinODEcosODEtanODE tanODESievelogODE recipCircleasinODEatanODEsqrtODEacosODEsinhODEcoshODEatanhODEpowODE fromFloatfromFixedPointshowPositionalDecshowPositionalHexshowPositionalBinshowPositionalBasisliftShowPosToInt toPositional magnitudesevalPowerSeries arctanSmallarctanpiConstexpSmalleConst recipEConst approxLogBaselnSmalllncons fromInteger'fromFloatBasisfromIntegerBasisfromRationalBasiscommonDenominatordefltDenominator defltShow solveDiffEq0 verifyDiffEq0 propDiffEq0 solveDiffEq1 verifyDiffEq1 propDiffEq1coeffs fromCoeffs$fCaT$fCaT0lift0fromPowerSerieslift1fromPowerSerieslift2fromPowerSeries swapVariablesdifferentiate0differentiate1 integrate0 integrate1isValidcheckfromPowerSeries0fromPowerSeries1diffComp logarithmic elemSym3_2 quadratic quadraticMVF quadraticDiff quadratic2quadraticDiff2 harmonicMVF harmonic2 harmonicDiff2 arithmeticMVF arithmetic2arithmeticDiff2 geometricMVF geometric2geometricDiff2meanValueDiff2degreeshowsExpressionPrec fromRoots translatefromPolynomial toPolynomialtoPolynomialFastrefinePolynomialconvolvePolynomial!convolveTruncatedPowerPolynomialssums fromElemSym divOneFlipfromElemSymDenormalized toElemSym toElemSymIntelemSymFromPolynomial binomials approxSeriespropOp toPowerSums fromPowerSumsaddRootliftPowerSum1GenliftPowerSum2Gen liftPowerSum1 liftPowerSum2liftPowerSumInt1liftPowerSumInt2addIntmulIntpowIntapproxPolynomial toRootSet commonDegree cardinalPower integerPower rationalPowerCyclecycleRightActioncycleLeftAction cycleAction cycleOrbit cyclesOrbitorbittakeUntilRepetitiontakeUntilRepetitionSlowkeepEssentials isEssentialcyclestoCyclestoTable fromTable liftCmpTable2 liftTable2 $fShowCycle $fReadCycle $fEqCyclefromFractionSum toFractionSum toFractiontoFactoredFractionmultiToFraction hornerRevfromFactoredFractionfromFactoredFractionAltmultiFromFraction reduceHeads carryRipplenormalizeModulo removeZerosmulFracmulFrac' mulFracStupidmulFracOverlap scaleFracscaleIntmulFastindexMapMapWithKeyindexMapToListindexMapFromList mapApplySplit Dimension transposerowscolumnsindexfromRows fromColumnsfromListformatnumRows numColumnsdiagonalrandomrandomR toMaybeScalartoScalarDefault toScalarShowTermConstAddDivmakeLine showUnitErrorlift scalarMap scalarMap2fromNumberWithDimensiontoNumberWithDimension&*&&/& mulToScalar divToScalarcancelToScalarunrecip absSignum*&rewriteDimension $fNFDataTnorm normFoldable normFoldable1normSqrnormSqrFoldablenormSqrFoldable1 defltNorm $fSqraComplex$fSqra[] $fSqra(,,) $fSqra(,)$fSqrTT$fSqrIntegerInteger $fSqrIntInt$fSqrDoubleDouble$fSqrFloatFloatPowerrealimag imaginaryUnitfromReal+:-: conjugate quarterRight quarterLeft signumNorm fromPolarcis propPolar magnitudeSqrphasetoPolardefltPow$fCaT1$fSqraT$fCaT2$fCaT3$fCaT4 $fPowerDouble $fPowerFloat+:: crossProduct similaritytoRotationMatrixfromRotationMatrixfromRotationMatrixDenormtoComplexMatrixfromComplexMatrixslerpexpon!fromShiftCoeffsfromPowerSeriesboundsseriesaddShiftedMany addShifted divExample equivalent identical isAbsoluteadjointSeriesBasisExponentDigitMantissa FixedPoint moveToZero checkPosDigit checkDigit nonNegativenonNegativeMantcompress compressFirst compressMantcompressSecondMant prependDigittrim trimUntiltrimOnce decreaseExp pumpFirst decreaseExpFP pumpFirstFP negativeExpfromBaseCardinalfromBaseInteger mantissaToNummantissaFromCardmantissaFromIntmantissaFromFixedIntfromBaseRational toFixedPointtoDouble fromDoublefromDoubleApproxfromDoubleRoughmantLengthDoubleliftDoubleApproxliftDoubleRoughshowDecshowHexshowBin showBasis powerBasis rootBasis fromBasis fromBasisMantcmp lessApproxtrunc equalApproxmean2withTwoMantissasalign alignMantabsoluteabsMant fromLaurent toLaurent liftLaurent2liftLaurentManyaddSomeaddMany seriesPlainsplitAtPadZerosplitAtMatchPadZerotruncSeriesSummands scaleSimple scaleMant mulSeriesdivMant divMantSlow reciprocal divIntMant divIntMantInfdivInt sqrtDriversqrtMantsqrtFP sqrtNewton sqrtFPNewton lazyInits expSeries expSeriesLazy expSmallLazyintPower cardPower powerSeries powerSmall cosSinhSmall cosSinSmall cosSinFourthcosSincotlnSerieslnNewton lnNewton' arctanSeries arctanStem arctanClassicminusOne sliceVertPairmantissacarry commonBasis defltBaseRoot defltBaseExp defltBase$fPowerT$fCTT0$fCTT1$fCTT2$fCTT3$fCTT4$fCTT5$fCT16strip$fCaMap$fCaMap0 $fSqraMap$fCaMap1$fCaMap2$fCaMap3$fCMap$fCMap0isScalar fromVectortoVectorratScale ratScaleMayberatScaleMaybe2ScalesymbolUnitSetunit independent defScaleIxscales InitScale initSymbolinitMag initIsUnit initDefault InitUnitSetinitUnitinitIndependent initScales extractOne initScale initUnitSet createScale createUnitSet showableUnitpowerOfUnitSet powerOfScaleshowExppositiveToFront decompose findIndep findClosestevalDist findBestExp findMinExpdistLE distances listMultiples $fShowUnitSet $fShowScaledistanceareavolumespeed accelerationforcepressureenergycurrent resistance capacitance angularSpeeddataRatepercentfourthhalf threeFourthsecondsPerMinutesecondsPerHour secondsPerDaysecondsPerYear meterPerInch meterPerFoot meterPerYardmeterPerAstronomicUnitmeterPerParseck2deg180grad200 radPerDeg radPerGradbytesizeaccelerationOfEarthGravitymach speedOfLight electronVoltcalorien horsePoweryoctozeptoattofemtopiconanomicromillicentidecidecahectokilomegagigaterapetaexazettayotta databaseRead databaseShowdatabase $fEqDimension$fOrdDimension$fEnumDimension$fShowDimensionsecondminutehourdayyearhertzmetergrammtonnecoulombvoltkelvinbitbyteinchfootyardastronomicUnitparsecquantityfromScalarSingle lift2Maybelift2GenerrorUnitMismatchaddMaybesubMayberatPow ratPowMaybe fromRatiomulPrecshowNat showSplit showScaled chooseScale showUnitPartdefScalefindCloseScale totalDefScalegetUnitreadsNat readUnitPart parseProductparseProductTail parsePower ignoreSpace createDictPValueliftGenliternewtonpascalbarjoulewattampereohmfaradbaudupdnpropUpCommutativepropDnCommutativepropUpAssociativepropDnAssociativepropUpDnDistributivepropDnUpDistributive$fCBool fastFractionsignedFraction==?deflt<*>.==?<=?>?>=?.<=>?<*>.<=?<*>.>=?<*>..>? zipWithPadmapLastzipWithCheckedzipWithOverlapmapLast' mapLast''GHC.NumNumFoldableMAC*.+multiplyAccumulaterunMacmultiplyAccumulateModulemakeMacmakeMac2makeMac3