@ J      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-. / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~                                          !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~             !!!!!!!!!!!!"""""""""""""""""""""""""""""""""""""""""######## # # # # ################### #!#"###$#%#&#'#(#)#*#+#,#-#.#/$0$1$2$3%4%5%6%7&8&9&:&;&<&=&>&?&@&A&B&C&D&E&F&G'H'I'J'K'L'M'N'O'P'Q'R'S'T'U'V'W'X'Y'Z'['\']'^'_'`'a'b'c'd'e'f'g'h'i'j'k'l'm'n(o(p(q(r(s)t)u)v)w)x)y)z){)|)}*~******++++++++++++++++++++++,,,,,,,,,,,,,,---------------------......................////////////////////////////////////////////////////// / / / / ///0000000000000111 1!1"1#1$1%1&1'1(1)1*1+1,1-1.1/101112131415161718191:1;1<=>?@ABCDEFGHIJKLMNO2P2Q2R2S2T2U2V2W2X2Y2Z2[2\2]2^2_3`3a3b3c3d3e3f3g3h3i3j3k3l3m3n3o3p3q3r3s3t3u3v3w3x3y3z3{4|4}4~4444444444444444444444444444444444444555555555555555555555555555555555555555555566666666666666666666666666666677777777777777777777777777777 7 7 7 8 8888899999999999999 9!9"9#9$9%9&9'9(9)9*9+9,9-9.9/90919293:4:5:6:7:8:9:::;:<:=:>:?:@:A:B:C:D:E;F;G;H;I;J;K;L;M;N;O;P;Q;R;S;T;U;V;W;X;Y;Z;[;\<]<^<_<`<a<b<c<d<e<f<g<h<i<j<k<l<m<n=o=p=q=r=s=t=u=v=w=x=y=z={=|=}=~==================>>>>>>>>>>>>?????????????????????????????@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@AAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBCCCCCCCCCCCCCC C C C C CCCCCDDDDDDDDDDDDDD D!D"D#D$D%D&D'D(D)D*D+D,D-D.D/D0D1D2D3D4E5E6E7E8E9E:E;E<E=E>E?E@EAEBECEDEEEFEGEHEIEJEKELEMENEOEPEQFRFSFTFUFVFWFXFYGZG[G\G]G^G_G`GaGbGcGdGeGfGgGhGiGjGkGlGmGnGoGpGqGrHsHtHuHvHwHxHyHzH{H|H}H~HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHIIIIIIIIIIIIIJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL L L M M MMMMMMMMMMMMMMMMMMM M!M"M#M$M%M&M'M(M)M*N+N,N-N.N/N0N1N2N3N4N5N6N7N8N9N:N;N<N=N>N?N@NANBNCNDNENFNGNHNINJNKNLNMNNNONPOQOROSOTOUOVOWOXOYOZO[O\O]O^O_O`OaObOcOdOeOfOgOhOiOjOkOlOmOnOoOpOqOrOsOtOuOvOwOxOyOzO{O|O}O~OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQ Q Q Q Q QQQQQQQQQQQQQQQQQQQ Q!Q"R#R$R%R&R'R(R)R*R+S,S-S.S/S0S1S2S3T4T5T6T7T8T9T:T;T<T=T>T?T@TATBTCTDTETFTGTHTITJTKTLTMTNTOTPTQTRTSTTTUTVTWTXTYTZT[T\T]T^T_U`UaUbUcUdUeUfUgUhUiUjUkUlUmUnUoUpUqUrUsUtUuUvUwUxUyUzU{U|U}U~UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUVVVVVVVVVVVVVVVVVVVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWXXXXXXXXXXYYYYYYYYZZZZZZZ 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 &Z 'Z (Z )Z *Z +Z ,Z -Z .Z /Z 0Z 1Z 2Z 3Z 4Z 5Z 6Z 7Z 8Z 9Z :[ ;[ <[ =[ >[ ?[ @[ A[ B[ C[ D[ E[ F[ G[ H[ I[aSafe{>This class allows defining instances that are exclusively for ; dimension. You won't want to define instances by yourself.>U 77(c) Henning Thielemann 2007$numericprelude@henning-thielemann.de provisionalportableSafed5Wrap an indexable object such that it can be used in Data.Map and Data.Set.pDefinition of an alternative ordering of objects independent from a notion of magnitude. For an application see MathObj.PartialFraction.If the type has already an 5 instance it is certainly the most easiest to define  to be equal to Ord's .Lift & implementation from a wrapped object. JSafe  \Safe K L M N O(c) Henning Thielemann 2006$numericprelude@henning-thielemann.de provisional7Routines and abstractions for permutations of Integers.Safe*CThere 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 ba cdfe_^nmlPLMORTQSN12(+$*)%./0&',-3456789:;<=>?@ABCDEFGHIJKUVWXYZ[\]`ghijkopqrstuvwxyz{|}~!t (+ba',-fedc @&B$)*%./0_^`nmlkDGE5wIH~z|[NSQTR;9:8?O\Xu2KMLCPF>=<Y734]Zv1Jighjxy{}WUpoAV6srq!(c) Henning Thielemann 2006$numericprelude@henning-thielemann.de provisional2Permutation represented by an array of the images.Safe*4+Extremely nave algorithm to generate a list of all elements in a group. Should be replaced by a Schreier-Sims system if this code is ever used for anything bigger than .. say .. groups of order 512 or so. "#$%&'()*+,- "#$%&'()*+,- Safeh.A reader monad for the special purpose of defining instances of certain operations on tuples and records. It does not add any new functionality to the common Reader monad, but it restricts the functions to the required ones and exports them from one module. That is you do not have to import both Control.Monad.Trans.Reader and Control.Applicative. The type also tells the user, for what the Reader monad is used. We can more easily replace or extend the implementation when needed. ./0123456 ./012345687./0]Safe. P/For atomic types this could be a superclass of . However for composed types like tuples, lists, functions we do elementwise comparison which is incompatible with the complete comparison performed by '(==)'. QIt holds 2(a ==? b) eq noteq == if a==b then eq else noteq:for atomic types where the right hand side can be defined. P Q R S T P Q^Safe3 U/For atomic types this could be a superclass of . However for composed types like tuples, lists, functions we do elementwise comparison which is incompatible with the complete comparison performed by . VIt holds f(compare a b) lt eq gt == case Prelude.compare a b of LT -> lt EQ -> eq GT -> gt:for atomic types where the right hand side can be defined. Minimal complete definition:  V or '(<=?)'. U W X Y V Z [ \ ] ^ _ ` a b c d e f U V Z X Y W Safe*} 9[Additive a encapsulates the notion of a commutative group, specified by the following laws: f 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 '(-)'): zero element of the vector space;add and subtract elements<add and subtract elements=inverse with respect to ;>> is (-)q with swapped operand order. This is the operand order which will be needed in most cases of partial application.?9Sum up all elements of a list. An empty list yields zero.QThis function is inappropriate for number types like Peano. Maybe we should make ?, a method of Additive. This would also make  lengthLeft and  lengthRight superfluous.@Sum 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.AtSum the operands in an order, such that the dependencies are minimized. Does this have a measurably effect on speed?Requires associativity.CqInstead of baking the add operation into the element function, we could use higher rank types and pass a generic  uncurry (+)g to the run function. We do not do so in order to stay Haskell 98 at least for parts of NumericPrelude.F |addPair :: (Additive.C a, Additive.C b) => (a,b) -> (a,b) -> (a,b) addPair = Elem.run2 $ Elem.with (,) <*>.+ fst <*>.+ sndPThe 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.9=<;:>?@ABCDEFGHIJKL9:;<=:;<;<=>?@ABCDEFGHJIKL9:;<=;6<6F4G4H4 Safe*й`WMaybe the naming should be according to Algebra.Unit: Algebra.Zero as module name, and query as method name.bJChecks if a number is the zero element. This test is not possible for all 93 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).`ab`abrqponmlkjihgfedc`a_Safe gFzip two lists using an arbitrary function, the shorter list is padded hVApply a function to the last element of a list. If the list is empty, nothing changes. gpadding value 8function applied to corresponding elements of the lists i8function applied to corresponding elements of the lists  g j i h k l Safe*sscRing encapsulates the mathematical structure of a (not necessarily commutative) ring, with the laws f a * (b * c) === (a * b) * c one * a === a a * one === a a * (b + c) === a * b + a * c JTypical examples include integers, polynomials, matrices, and quaternions.Minimal definition: t, (u or v)wThe 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 2V. 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 w& with more flexibility is provided by ab.8Commutativity need not be satisfied by all instances of s. swvutxyz{|}~stuvwtuvwxyz{|}~stuvwt7w8  (c) Henning Thielemann 2004-2005$numericprelude@henning-thielemann.de provisionalportableSafe*ZWe need a Haskell 98 type class which provides equality test for Vector type constructors.A Module over a ring satisfies: f a *> (b + c) === a *> b + a *> c (a * b) *> c === a *> (b *> c) (a + b) *> c === a *> c + b *> c zero element of the vector spaceadd and subtract elementsscale a vector by a scalar4Compute the linear combination of a list of vectors. 467Safe*;=>?77(c) Henning Thielemann 2009-2010, Mikael Johansson 2006$numericprelude@henning-thielemann.de provisionalAbstract concept of a Monoid.SafefWe 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 classesSafe*  (c) Henning Thielemann 2007-2010haskell@henning-thielemann.destable Haskell 98SafexInstances of this class must ensure non-negative values. We cannot enforce this by types, but the type class constraint  NonNegative.CC avoids accidental usage of types which allow for negative numbers.9The Monoid superclass contributes a zero and an addition.split 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)Rthat 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 Nlet (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.,Default implementation for wrapped types of  and  m class. x -| y == max 0 (x-y)pThe default implementation is not efficient, because it compares the values and then subtracts, again, if safe.  max 0 (x-y)K is more elegant and efficient but not possible in the general case, since x-y% may already yield a negative number.66Safe*,&IntegralDomain* 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 )'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]FReturns the result of the division, if divisible. Otherwise undefined.FReturns the result of the division, if divisible. Otherwise undefined.\Allows division by zero. If the divisor is zero, then the dividend is returned as remainder. 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. 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. divUp n m is similar to div* but it rounds up the quotient, such that divUp n m * m = roundUp n m.77Safe*:2This 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 y 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 0Currently some algorithms assume this property. Safe*^ A 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)OMinimal definition: * nothing, if the standard Euclidean algorithm work * if  is implemented customly,  and  make use of itTCompute the greatest common divisor and solve a respective Diophantine equation. F (g,(a,b)) = extendedGCD x y ==> g==a*x+b*y && g == gcd x ypTODO: 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.*The Greatest Common Divisor is defined by: q gcd x y == gcd y x divides z x && divides z y ==> divides z (gcd x y) (specification) divides (gcd x y) xLeast common multiplehCompute the greatest common divisor for multiple numbers by repeated application of the two-operand-gcd."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.Like , but aL is minimal with respect to the measure function of the Euclidean algorithm. nNot efficient because it requires duplicate computations of GCDs. However GCDs of neighbouring list elements were not computed before. It is also quite arbitrary, because only neighbouring elements are used for balancing. There are certainly more sophisticated solutions.8Not efficient enough, because GCD/LCM is computed twice.For >Just (b,n) = chineseRemainder [(a0,m0), (a1,m1), ..., (an,mn)] and all x with  x = b mod n the congruences *x=a0 mod m0, x=a1 mod m1, ..., x=an mod mn are fulfilled.          Safe*bNothing is the smallest element.Nothing is the largest element.#-It is only a monoid for non-negative numbers. idt <*> GCD (-2) = GCD 24Thus, use this Monoid only for non-negative numbers!  !"#$%#$%& !"'() !"#$%Safe*g23M is a general differentation operation It must fulfill the Leibnitz condition D differentiate (x * y) == differentiate x * y + x * differentiate yVUnfortunately, this scheme cannot be easily extended to more than two variables, e.g. MathObj.PowerSeries2.232323Safe*~>4XThis is the type class of a ring with a notion of an absolute value, satisfying the laws l a * b === b * a a /= 0 => abs (signum a) === 1 abs a * signum a === aMinimal definition: 5, 6.If the type is in the  class we expect 5 = 7 and 6 = 8* 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.5 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 Lcz. This type class is intended for unifying algorithms that work for both real and complex numbers. Note the similarity to  Algebra.Units: 5 plays the role of  stdAssociate and 6 plays the role of stdUnit.Actually, since 5 can be defined using  and =$ we could relax the superclasses to Additive and ! if his class would only contain 6.4567845678456G(c) Henning Thielemann 2011-2012 (c) Dylan Thurston 2006$numericprelude@henning-thielemann.de provisional portable (?)Safe*M similar to #d PbThis is an alternative show method that is more user-friendly but also potentially more ambigious.QONecessary when mixing NumericPrelude.Numeric Rationals with Prelude98 Rationals FGHIJKLMNOPQ GHIJNFKOLMPQGHIJN7Safe*t`ZField again corresponds to a commutative ring. Division is partially defined and satisfies U 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: b or (a)e*Needed to work around shortcomings in GHC.f)the restriction on the divisor should be isUnit a instead of not (isZero a)`dcbaefg `abcdabcedfg`abcda7d8None*mYThis class allows lossless conversion from any representation of a rational to the fixed FB 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 === idn=Lossless conversion from any representation of a rational to FoIt should hold (realToField = fromRational' . toRationalWbut it should be much more efficient for particular pairs of types, such as converting ! to  #. This achieved by optimizer rules.mnomn|{zyxwvutsrqpomnSafe*}Remember 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 required}~}~}~~77NoneThe two classes  and `a exist to allow convenient conversions, primarily between the built-in types. They should satisfy K fromInteger . toInteger === id toRational . toInteger === toRationalVConversions 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.A prefix function of '(Algebra.Ring.^)' with a parameter order that fits the needs of partial application and function composition. It has generalised exponent.See: Argument order of expNat on Hhttp://www.haskell.org/pipermail/haskell-cafe/2006-September/018022.htmlIA prefix function of '(Algebra.Field.^-)'. It has a generalised exponent.0(c) Dylan Thurston, Henning Thielemann 2004-2005$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone*;=>?A Module over a ring satisfies: f a *> (b + c) === a *> b + a *> c (a * b) *> c === a *> (b *> c) (a + b) *> c === a *> c + b *> cscale a vector by a scalar4Compute the linear combination of a list of vectors.ToDo: Should it use (i ?(This function can be used to define any 9 as a module over #.Better move to Algebra.Additive?7None*;=>? None*;=>?LDivisibleSpace 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*;=>? It must hold: r Module.linearComb (flatten v `asTypeOf` [a]) (basis a) == v dimension a v == length (flatten v `asTypeOf` [a])jbasis of the module with respect to the scalar type, the result must be independent of argument, gj should suffice. scale a vector by a scalaruthe size of the basis, should also work for undefined argument, the result must be independent of argument, gj should suffice.  !None*[Minimal implementation:  or '(^/)'.  8"None*Transcendental 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.xNote the default declaration for a superclass. See the comments below, under "Instance declaractions for superclasses".UThe semantics of these operations are rather ill-defined because of branch cuts, etc.KMinimal complete definition: pi, exp, (log or logBase), sin, cos, atan')88#None*Y"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 u doesn't return the integer part of the number. This also removes a type ambiguity if the integer part is not needed.tMany people will associate rounding with fractional numbers, and thus they are surprised about the superclass being Ring not FieldY. 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 #D in FixedPoint-fractions module. They are even reasonably efficient.EI am still uncertain whether it was a good idea to add instances for Integer and friends, since calling floor or fractionb on an integer may well indicate a bug. The rounding functions are just the identity function and B is constant zero. However, I decided to associate our class with Ring rather than FieldW, 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).HFor 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, oneE 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 G denominator type supports , every G can provide  and -, e.g. fractions of polynomials. However the Ring constraint for the ' integral' part of m 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.1This 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.6TODO: Should be moved to a continued fraction module. "The 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. 7Needs linear time with respect to the number of digits.2This and other functions using OrderDecision like floorE where argument and result are the same may be moved to a new module.!      !..-,+*)('&%$#"      !$None*/nThis is a convenient class for common types that both form a field and have a notion of ordering by magnitude.//%None*O3VThis class collects all functions for _scalar_ floating point numbers. E.g. computing 47 for complex floating numbers makes certainly no sense.34346534&None*7Counterpart of gl$ but with NumericPrelude superclass.789;<DCBA@>=:?789:;<=>?@ABCDFE7 89:;<=>?@ABCD'NoneKG{This makes a type usable in the NumericPrelude framework that was initially implemented for Haskell98 typeclasses. E.g. if a is in class  m, then T a is both in class  m and in s.&You can even lift container types. If  Polynomial a is in  m for all types a that are in  m, then 3T (Polynomial (MathObj.Wrapper.NumericPrelude.T a)) is in s for all types a that are in s.GHIJKLMNGHIJKLM`_^]\[ZYXWVUTSRQPONGHI(None*)nlTaken number of elements must be at most the length of the list, otherwise the end of the list is undefined.onDropped number of elements must be at most the length of the list, otherwise the end of the list is undefined.p}Split position must be at most the length of the list, otherwise the end of the first list and the second list are undefined.qYThe index must be smaller than the length of the list, otherwise the result is undefined.rZip 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.r8function applied to corresponding elements of the lists nopqrnopqr)None*,wGLeft associative length computation that is appropriate for types like Integer.xHRight associative length computation that is appropriate for types like Peano number. qstuvwxyz{| qwxstuv{y|zNone*-bR !"#:=<;>?@awvutxyz65FJINdcbaen~4|;<;<=:>?@atuvwxyzabcde56~~4nFNIJ#"! *None*2NThe 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*4kT is a Reader monad but does not need functional dependencies like that from the Monad Transformer Library.,None*?2+Here we try to provide implementations for : and u 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 u can be found ResidueClass.=the modulus can be Nothing to denote a generic constant like : and u6 which could not be bound to a specific modulus so farr /: m! is the residue class containing r with respect to the modulus m3Check if two residue classes share the same modulus  77-None*CiHere 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*LThe best solution seems to let N be part of the type. This could happen with a phantom type for modulus and a run function like mnQ. Then operations with non-matching moduli could be detected at compile time and  and l could be generated with the correct modulus. An alternative trial can be found in module ResidueClassMaybe.r /: m! is the residue class containing r with respect to the modulus m3Check if two residue classes share the same modulus77/ (c) Henning Thielemann 2007-2012$numericprelude@henning-thielemann.de provisionalportableNone*Y3If all values are completely defined, then it holds "if b then x else y == ifLazy b x y However if bH is undefined, then it is at least known that the result is larger than min x y.ycf. To how to find the shortest list in a list of lists efficiently, this means, also in the presence of infinite lists. Fhttp://www.haskell.org/pipermail/haskell-cafe/2006-October/018753.html*On equality the first operand is returned.*On equality the first operand is returned.x0 <= x1 && x1 <= x2 ... / for possibly infinite numbers in finite lists.In 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.Chunky"Compute '(&&)' with minimal costs.!7 30None*[~ o1 (c) Henning Thielemann 2007-2010haskell@henning-thielemann.destable Haskell 98NoneoA 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.$Remove zero chunks.(divModLazy 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.)hThis function has a strict divisor and maintains the chunk structure of the dividend at a smaller scale.1 is implemented in terms of )z. 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.  !"#$%&'() "# !'$%&() p q(c) Henning Thielemann 2007haskell@henning-thielemann.destable Haskell 98None*w>]Convert a number to a non-negative number. If a negative number is given, an error is raised.@Convert 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. r'Results are not checked for positivity. s'Results are not checked for positivity.?=name of the calling function to be used in the error message <=>?@ >?@=<2None*>?xOPQRSTUOPQR]\[STUZYXWVOPQ3None*x_6Horner's scheme for evaluating a polynomial in a ring.`8Horner's scheme for evaluating a polynomial in a module.b9It's also helpful to put a polynomial in canonical form. b+ strips leading coefficients that are zero.c*Multiply by the variable, used internally.mm7 is fast if the second argument is a short polynomial, 9q relies on that fact.qThe 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].v~Integrates if it is possible to represent the integrated polynomial in the given ring. Otherwise undefined coefficients occur._`abcdefghijklmnopqrstuvwxyz_`abcdefghijklmnopqrstuvwxzy4None*"For the series of a real function f compute the series for  x -> f (-x)"For the series of a real function f compute the series for x -> (f x + f (-x)) / 2"For the series of a real function f compute the real series for x -> (f (i*x) + f (-i*x)) / 2For power series of f x, compute the power series of f(x^n).Divide 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 algorithms8Divide two series also if the divisor has leading zeros.We 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.NInput series must start with a non-zero term, even better with a positive one.The first term needs a transcendent computation but the others do not. That's why we accept a function which computes the first term. Y(exp . x)' = (exp . x) * x' (sin . x)' = (cos . x) * x' (cos . x)' = - (sin . x) * x'+Input series must start with non-zero term. Computes (log x)' , that is x'/xNSince the inner series must start with a zero, the first term is omitted in y.Compose 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.mThis 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)Rwhere 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.({|}~({|}~5None*8Power series of error function (almost). More precisely 1 erf = 2 / sqrt pi * integrate (x -> exp (-x^2)) , with  erf 0 = 0.++6(c) Henning Thielemann 2006$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone*Rdenominator conversion@very efficient because it can make use of the decimal output of m7None*denominator conversion    8None* DExample 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.We 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*;=>?"Evaluate (truncated) power series."Evaluate (truncated) power series.GEvaluate approximations that is evaluate all truncations of the series. GEvaluate approximations that is evaluate all truncations of the series.!GEvaluate approximations that is evaluate all truncations of the series."It fulfills 3 evaluate x . evaluate y == evaluate (compose x y)  !"#$ 10 !/.-,+*)('&%"#$:None*DNSince the inner series must start with a zero, the first term is omitted in y.3456789:;<=>?@ABCD3456789:;<=>?@ABCD;None*;=>?E}In order to handle both variables equivalently we maintain a list of coefficients for terms of the same total degree. That is Feval [[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.EFGHIJKLMNOPQREFGHIJKLMNOPQZRYXWVUTSEFG<None*\]^_`abcdefghijklm\]^_`abcdefghijklm=None*;=>?0tnHere the coefficients are vectors, for example the coefficients are real and the coefficents are real vectors.uHere the argument is a vector, for example the coefficients are complex numbers or square matrices and the coefficents are reals.vv. is the functional composition of polynomials.It fulfills ' eval x . eval y == eval (compose x y) tIt is disputable whether polynomials shall be represented by number literals or not. An advantage is, that one can write let x = polynomial [0,1] in (x^2+x+1)*(x-1) However the output looks much different.The * instance is intensionally built from the `; structure of the polynomial coefficients. If we would use  Integral.C ab superclass, then the Euclidean algorithm could not determine the greatest common divisor of e.g. [1,1] and [2].nopqrstuvwxyz{|}~nopoqrwstuxyvz{|~}n uo>None*ڕ$Determine mask by Gauss elimination.ZR - alternating binomial coefficients L - differences of translated polynomials in columnsp2 = L * R^(-1) * mR * L^(-1) * p2 = m*If the mask does not sum up to a power of 1/2 then the function returns ).)Convolve polynomials via refinement mask.=(mask x + ux*(-1,1)^degree x) * (mask y + uy*(-1,1)^degree y)   v? (c) Henning Thielemann 2004-2005$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone*;=>?*@ (c) Henning Thielemann 2004-2005$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone*cf. =r Given 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. ANonexoThe root degree must be positive. This way we can implement multiplication using only multiplication from type a.exponent must be non-negativeexponent can be negativeexponent must be positive 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*nRight (left?) group action on the Integers. Close to, but not the same as the module action in Algebra.Module.candidates for Utility ?C(c) Henning Thielemann 2006$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone*We 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.5Does not check whether the input values are in range. TThese instances may need more work They involve converting a permutation to a table.      D(c) Henning Thielemann 2007$numericprelude@henning-thielemann.de provisionalportableNone* JCons 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.Unchecked construction.s`< is not really necessary here and only due to invokation of .s`< is not really necessary here and only due to invokation of N.fromFactoredFraction x y1 computes the partial fraction representation of  y % product x, where the elements of xp 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.JThe list of denominators must contain equal elements. Sorry for this hack.aA normalization step which separates the integer part from the leading fraction of each sub-list. Cf. Number.Positional!A normalization step which reduces all elements in sub-lists modulo their denominators. Zeros might be the result, that must be remove with "."RRemove 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.$Transforms a product of two partial fractions into a sum of two fractions. The denominators must be at least relatively prime. Since D requires irreducible denominators, these are also relatively prime. Example: mulFrac (1%6) (1%4)% fails because of the common divisor 2.&@Works always but simply puts the product into the last fraction.'`Also works if the operands share a non-trivial divisor. However the results are quite arbitrary.(AExpects an irreducible denominator as associate in standard form./aApply a function on a specific element if it exists, and another function to the rest of the map. !"#$%&'()*+,-./!2 !"#1$%&'()*+0,-./E2(c) Henning Thielemann 2009, Mikael Johansson 2006$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone*;=>?&g58A matrix is a twodimensional array, indexed by integers.6JTransposition of matrices is just transposition in the sense of Data.List.456789:;<=>?@ABCDEFG54=6789:;<>?@ABCDEFG5 wFNone*;=>?'xQSTRUVQRSTUVXWQRSTGNone*;=>?,^A 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. Y][\Z^_`abcdef^_YZ[\]`abcdefqponmlkjihgYZ[\]^_HNone;=>?-(rstuvwxyz{|}~0|}~{zyxwvutsr|}777INone*;=>?43The 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 Default definition for  that is based on  x class.Default definition for  that is based on  x: class and the argument vector has at least one component. JNone*;=>?7Default definition for  that is based on  x class.Default definition for  that is based on  x: class and the argument vector has at least one component. KNone*;=>??t<A vector space equipped with an Euclidean or a Hilbert norm.Minimal definition: Euclidean norm of a vector. Helper class for & that does not need an algebraic type a.Minimal definition: WSquare of the Euclidean norm of a vector. This is sometimes easier to implement. Default definition for  that is based on  x class.Default definition for  that is based on  x: class and the argument vector has at least one component.L"(c) The University of Glasgow 2001/BSD-style (see the file libraries/base/LICENSE)$numericprelude@henning-thielemann.de provisional portable (?)None*;=>?c(We 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.&Complex numbers are an algebraic type. real partimaginary part8Construct a complex number from real and imaginary part.7Construct a complex number with negated imaginary part."The conjugate of a complex number.(Scale a complex number by a real number.DExponential of a complex number with minimal type class constraints.(Turn the point one quarter to the right.(Turn the point one quarter to the right.&Scale a complex number to magnitude 1.For a complex number z, 5 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.CForm a complex number from polar components of magnitude and phase. t# is a complex value with magnitude 1 and phase t (modulo 2*). yThe nonnegative magnitude of a complex number. This implementation respects the limited range of floating point numbers. The trivial implementation  would overflow for floating point exponents greater than the half of the maximum admissible exponent. We automatically drop in this implementation for ! and  K by optimizer rules. You should do so for your custom floating point types.,The phase of a complex number, in the range (-, ]2. If the magnitude is zero, then so is the phase. 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. zSpecial implementation of (/)D for floating point numbers which prevent intermediate overflows. The '(*>)' method can't replace 5 because it requires the Algebra.Module constraint { {66M$numericprelude@henning-thielemann.de provisional portable (?)None*;=>?~ Quaternions could be defined based on Complex numbers. However quaternions are often considered as real part and three imaginary parts.  real part imaginary parts4Construct a quaternion from real and imaginary part.The conjugate of a quaternion.$Scale a quaternion by a real number. |6like Module.*> but without additional class dependencyFthe same as NormedEuc.normSqr but with a simpler type class constraint)scale a quaternion into a unit quaternion4similarity mapping as needed for rotating 3D vectors It holds Gsimilarity (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.Let c% be a unit quaternion, then it holds .similarity c (0+::x) == toRotationMatrix c * xrThe rotation matrix must be normalized. (I.e. no rotation with scaling) The computed quaternion is not normalized.Map 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.Revert .Spherical Linear InterpolationyCan be generalized to any transcendent Hilbert space. In fact, we should also include the real part in the interpolation. The '(*>)' method can't replace 5 because it requires the Algebra.Module constraintFor 0 return vector v, for 1 return vector w vector v, must be normalized vector w, must be normalized         }   }66N (c) Henning Thielemann 2004-2006$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone*;=>?Z*(Polynomial including negative exponents :Add 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 S or with T, S would be straightforward, but more time consuming (quadratic time) whereas foldr is not so obvious but needs only linear time.Y(stars denote the coefficients, frames denote what is contained in the interim results) S sums this way: | | | ******************************* | | +-------------------------------- | | ************************ | +---------------------------------- | ************ +------------------------------------I.e. SK would use much time find the time differences by successive subtraction 1.T mixes this way:  +-------------------------------- | ******************************* | +------------------------- | | ************************ | | +------------- | | | ************A[Two polynomials may be stored differently. This function checks whether two values of type LaurentPolynomial( actually represent the same polynomial.CnCheck whether a Laurent polynomial has only the absolute term, that is, it represents the constant polynomial.Dp(z) -> p(-z) Ep(z) -> p(1/z) F%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.*+,-./0123456789:;<=>?@ABCDEF&*+,-./0123456O7N89:;<=MLKJ>I?H@AGBCDEF*+,-ONone**-ZConverts 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!)[Requires, that no digit is  (basis-1) or  (1-basis)3. The leading digit might be negative and might be -basis or basis.\May prepend a digit.]*Compress first digit. May prepend a digit.^Does not prepend a digit._uCompress second digit. Sometimes this is enough to keep the digits in the admissible range. Does not prepend a digit.a7Eliminate leading zero digits. This will fail for zero.b9Trim until a minimum exponent is reached. Safe for zeros.dhAccept a high leading digit for the sake of a reduced exponent. This eliminates one leading digit. Like e but with exponent management.e>Merge leading and second digit. This is somehow an inverse of ^.hMake 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.p'Split into integer and fractional part.scf. uvt^Only return as much digits as are contained in Double. This will speedup further computations.y$Show a number with respect to basis 10^e.}Convert from a b basis representation to a b^e basis.Works well with every exponent.~Convert from a b^e basis representation to a b basis.Works well with every exponent.OConvert between arbitrary bases. This conversion is expensive (quadratic time).)The 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.3If all values are completely defined, then it holds "if b then x else y == ifLazy b x y However if bD is undefined, then it is at least known that the result is between x and y. 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 bBGet the mantissa in such a form that it fits an expected exponent.x and (e, alignMant b e x) represent the same number.3Add two numbers but do not eliminate leading zeros. Add at most basis> summands. More summands will violate the allowed digit range._Add many numbers efficiently by computing sums of sub lists with only little carry propagation.Add 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.Like yJ, but it pads with zeros if the list is too short. This way it preserves ) length (fst (splitAtPadZero n xs)) == n help showing series summandsFor 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.Undefined 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.TToDo: Rigorously derive the minimal required magnitude of the leading divisor digit.`Fast division for small integral divisors, which occur for instance in summands of power series. 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 U.XToDo: 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 basisRth 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) ?uNewton 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.gOptimal 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.List.inits is defined by -inits = foldr (x ys -> [] : map (x:) ys) [[]]'This is too strict for our application. SPrelude> 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-htX package, but it is restricted to infinite lists. This degree of laziness is needed for sqrtFP. bPrelude> lazyInits (0:1:2:undefined) [[],[0],[0,1],[0,1,2],[0,1,2,*** Exception: Prelude.undefined-Absolute value of argument should be below 1.MResidue estimates will only hold for exponents with absolute value below one.The computation is based on "U, 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.-Absolute value of argument should be below 1.-Absolute value of argument should be below 1.Like  but converges faster. It calls  cosSinSmall; with reduced arguments using the trigonometric identities e 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.CThe same could be achieved with a fourth power of a complex number. 9x' = x - (exp x - y) / exp x = x + (y * exp (-x) - 1) oFirst, 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 IPossibly 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.This is an inverse of , also known as atan2v with flipped arguments. It's very slow because of the computation of sinus and cosinus. However, because it uses the 4] 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.9Arcus tangens of arguments with absolute value less than  1 / sqrt 3.BEfficient computation of Arcus tangens of an argument of the form 1/n.jThis implementation gets the first decimal place for free by calling the arcus tangens implementation for  s."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.PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~πVUTSRQWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~PPNone*@ 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)) == e0. 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-1v. The representation is not unique and cannot be made unique in finite time. This way we avoid infinite carry ripples.|Shift 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)K. The result is still not unique, but may be useful for further processing.7perfect carry resolution, works only on finite numbers #QNone>?KGL|This makes a type usable with Haskell98 type classes that was initially implemented for NumericPrelude typeclasses. E.g. if a is in class s, then T a is both in class  m and in s.&You can even lift container types. If  Polynomial a is in s for all types a that are in s, then .T (Polynomial (MathObj.Wrapper.Haskell98.T a)) is in  m for all types a that are in  m. RNone*;=>?H"$Remove all zero values from the map." "*)('&%$#SNone*T+A 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.,The neutral Unit.T-Test for the neutral Unit.T.RConvert a List to sparse Map representation Example: [-1,0,-2] -> [(0,-1),(2,-2)]/Convert Map to a List+,-./012+,-./012TNone*b3A common scaling for a unit.7'An entry for a unit and there scalings.<,If True the symbols must be preceded with a 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. PARaise all scales of a unit and the unit itself to the n-th power S`Reorder the unit components in a way that the units with positive exponents lead the list. T)Decompose a complex unit into common onesYMFind the exponent that lead to minimal distance Since the list is infinite M^ will fail but the sequence is convex and thus we can abort when the distance stop fallingW;(UnitSet,distance) the UnitSet may contain powered units *345678;:=<9>?CBA@DEHGFIJKLMNOPQRSTUVWXYZ[\*IDEFGH>?@ABC789:;<=3456JKLMNOPQRSTUVWXYZ[\3456789:;<=>?@ABCDEFGHUNone*rgSome common quantity classes.hSome common quantity classes.iSome common quantity classes.jSome common quantity classes.kSome common quantity classes.lSome common quantity classes.mSome common quantity classes.nSome common quantity classes.oSome common quantity classes.pSome common quantity classes.qSome common quantity classes.rSome common quantity classes.sSome common quantity classes.tSome common quantity classes.uSome common quantity classes.vSome common quantity classes.wSome common quantity classes.xSome common quantity classes.ySome common quantity classes.zSome common quantity classes.{Some common quantity classes.|Some common quantity classes.}Some common quantity classes.~Common constantsConversion factorsPhysical constantsPrefixes used for SI units2UnitDatabase.T of units and their common scalings 2UnitDatabase.T of units and their common scalings P_fedcba`ghijklmnopqrstuvwxyz{|}~P_`abcdefyzghijklmnopqrstuvwx{|}~_`abcdefVNone*u((WNone*;=>?}IA Physics.Quantity.Value.T combines a numeric value with a physical unit.^Construct a physical value from a numeric value and the full vector representation of a unit.4Test for the neutral Unit.T. Also a zero has a unit!?apply a function to the numeric value while preserving the unit;Add two values if the units match, otherwise return Nothing@Subtract two values if the units match, otherwise return Nothing!XNone*(`Show the physical quantity in a human readable form with respect to a given unit data base. Returns 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 lChoose a scale where the number becomes handy and return the scaled number and the corresponding scale. unused unused  YNone*xlThis function could also return the value, but a list of pairs (String, Integer) is easier for testing. ZNone*;=>?K(/                           ! " # $ % & '@  8 7  6  5 4 3 2 1 0 / . - , + *                        ! # $ % & ' " ) ([None*5 : ; < = > ? @ A B C D E : ; < C D E = > ? @ A B : ; < ;5 <5yNone ba cdfe_^nmlTPOSQRMLN21(+ !"#$*)%./0&',-3456789:;<=>?@ABCDEFGHIJKUVWXYZ[\]`ghijkopqrstuvwxyz{|}~!;<=:>?@atwvuxyz6FIJNabdcen~4 C D E C D EzNone;=>? A special reader monad. The 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.7We 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. H(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 Ilerpnorm 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. Infix variant of  .       6 {|}~{{{{{{|{|{|{{{{~~{|{|{|{|{|{{{~{|{|~{{~~~~~{|~~{~{|{|~{{~~~{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{i{{{{{{ { { { { {{{{{{{{{{{{{{{{{|{| {|!{|"{|#{|${|%{|&{|'{|({)j{)*~+~,~-~.~/~0~1~2~3~456756856956565656:;<=>>?@@AABBCCDDEEFFGHIJKKLLMM`NOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~`,`9 9           `                                       `                   `                                   `           ``9i``h     ` !"#$%&`'()*+,-./0123456789:;<=>?@ABBCDDEFFGHHIJKLMNOPQRSTU`V`WXYZ[9\]^_`aRbcdefghijkl`mRnopqr`st`uvw`xybz`{|}~`}~` `            !`!!t!!!!!!!!!"`"""""q"""""""""""""""""""""""""""""""""""#`#d############################################$`$$$%`%%%&`&&&&&&&&`&&&&&&&'9'''''''''''k'l''''''''''''''''j''''e''d''''( ( ( ((i)) ) ) ))))))****Q***R+9++ + + + + +++++++++++++++,9,,,,,,,,,,,,,i-9-- - - ------!-"-#-$---e----k.9....%...&. ...'.......k..i./(/(/)/*/9/+/,/-/./////Q/0/1/2/3/4/5/6/7/8/9/:/;/</=/>/?/@/A/B/"///e//////k/l//////j////////i//C/D/E090F0_0d0e0000k0l00j0191G1H1I1J1K171L1M1N1O1P1Q11R1S1d1e1h1111k1l111111j1[TKUVkl29222O2{22W22222k2g2h223X3Y3Z3L3[3\3!3333`3]3^3_3Q3`3a33b33c3V3d3e3r3f3g3h4i4j4k4l4m4n4f4o4p4q4444`4Q4r444s4c4t4V4d44u44v4w44444x44444y4z4{5R555555555555u55|5}5~5555555555555555555555555566666666666Q66R666t666666666666667977^7]7777n77777 7777O777d7e777j777k7l7777888888999999 999$9O99i9j9k9l9m9n99g9h9999k9l999999999j:9:::::::`:Q:::u::::::;9;;;;;;;; ;;;$;;O;;;;k;l;;;;j<<<<<<<<<<<<<<<<<<=9=====i=j=k==$=]=d====g=h=d=e=h====k=l=========>9>>>>>>>>>h>>?9??? ???$?????????O??Q?u?t????????k?@9@@@ @@@$@@@@@@@@@@@@@O@@@Q@@u@@@@@@k@A9AAKA7AAAQAhARAAAAtAAjAAAB9BBBBBBBBBB B BB B BC9CCC CCCCCCCC'CCCCCCjCCCCCD9DDDDODDDDDDDD_DD D!D"DiD#D$D%D&D'D(DQD)D*D+D,D-DDDDE.E9E/E0E1E2E3E4E5E6EE7E8EiEEE9E`E:E;EEEEEEEEjEiF`FHF<FIF=F>FFG?G@GAGLGBG9GG_GCGDGEGIGFGGGGGGGkGlGGGjGGH>H?H@HAHBHCHDHEHFHMH9HHKH7HHHIHJHKHLHMHNHRHOHHHWHPH`HQHRHPHHdHeHfHjHgHhHiHkHfHHHHHHSHHHjI`ITIUIVI}IIIIIIIIJ`JTJUJVJ}JJJJJJJJK`KTKJKWKXKYKZK[K\K]K^K_K`KaKbKcK}KKKKKKKLdLL9LeLfLgLhLiLjLkL`LLlLmLXLnLoLpLqLcLrLsLtLuLdLeLLLLkLLLvLwLxLyLzLlLLLLLLgLhLLiLLLL{L|LM9MeMfMhM}MkM`MWMTMLMM~MMMMMMMMMMMMMkMlMvMwMiMMN9NNNN$NNNNNNN[NNONNNNNNNQNhNNNNNfNNNNNNNNNkNNOOOOOOO9OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO2OOOOOOOOOOOOOOOOOOOOO`OOOOQOOOOOOOOOOOOOOOOOOOOOOOOOtOOOOOOOOOOOOgOOOOOOOOOOOOP9PP{PPPPPP PPPPPPPPPPdPePPPPPkPjPPlPPPPPPPPQ9QQQQQQQQQ_QQQQQQQQQdQQeQQQQjQQQQQQQkQlQQQQQQQQQQQQQRRR R R R R RRS9SPSSSSSSTTTTcTTTTTTTTTTTT T!T"T"T#T$T%T9T&T'T(T)T*T+T,T-T.T/T0T1T2T3T4T5T6T7T8T9T:U.UFUEUDUCUBUAU@UU;U<U=UdUjU>U?UeU@UAUBUUfUCUkUDUEUgUFUhUiUGUHUIUJUKULUMUNUOUPUQURUSUTUUUVUWUXUYUZU[U\U]U^U_U`UaUbUcUdUeUfUgUhUiUjUUkUlUmUnUoUpUqUrUsUtUuUvUwUxUyUzU{V|V}V~VVVVVVVVVVVVVVVVW9WWWWWEWWWWWWW`WWWWWWWWWvWWWWkWlWjWWWWWXXXXXXXXXXYYYYYYYYZZ9ZZEZZZZ`ZZZZZZ|Z}Z~ZZZZZZZZZZZZZZZZZZZZZZZZZZ[Z\Z]Z^Z_Z`ZdZeZZZvZZZZkZlZjZZZiZZZZ[`[[[[[[[[[3[4[W[[[[\\\\\]`]]]]^`^,^^^^^3^4^^^^^^^^^^______{011E="=>E{LLLMM{xzz`zzzzz+zzzzzz,numeric-prelude-0.4.3-Ef0bs5KKkdsCfYuKSyB4zaNumericPrelude.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==>=fail>>=>>fmapreturnGHC.Real realToFracBoundedEnumEqMonadFunctorOrdGHC.ReadReadGHC.ShowShow GHC.TypesBoolCharDoubleFloatInt integer-gmpGHC.Integer.TypeIntegerMaybeOrderingIO Data.EitherEitherFalseNothingJustTrueLeftRightLTEQGTData.TraversablesequencemapMreadIOreadLn appendFile writeFilereadFileinteract getContentsgetLinegetCharputStrLnputStrputCharGHC.IO.ExceptionioErrorGHC.IOFilePath userErrorIOError Data.FoldablenotElemallanyorand concatMapconcat sequence_mapM_minimummaximumelemlengthnullfoldl1foldr1foldlfoldr Data.OldListunwordswordsunlineslines Text.Readreadreadseitherlex readParenreadList readsPrecText.ParserCombinators.ReadPReadSmaxBoundminBoundfromEnumtoEnumpredsucc showParen showStringshowCharshowsShowSshowListshow showsPrecunzip3unzipzipWith3zip3!!lookupreversebreakspansplitAtdroptake dropWhile takeWhilecycle replicaterepeatiteratescanr1scanrscanl1scanlinitlasttailhead Data.MaybemaybeuncurrycurryasTypeOfuntil$!flip.constid=<<<$StringGHC.Errerror/=compare<=&&||not<>maxmin)non-negative-0.1.2-EXUt2er1wE98Q5e7Iin6KGNumeric.NonNegative.WrappertoNumberfromNumberUnsafeT(utility-ht-0.0.14-1SDJ0BtW7GoAaRrxZT3hIqData.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 $fShowGCD$fEqGCD $fShowLCM$fEqLCM $fShowMin$fEqMin $fShowMax$fEqMax 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 $fShowScale $fShowUnitSetdistanceareavolumespeed 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.NumNumdiophantineMultiMinFoldablefloatMagnitude floatDivide scaleImagMAC*.+multiplyAccumulaterunMacmultiplyAccumulateModulemakeMacmakeMac2makeMac3