hW      !"#$%&'()*+,-./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 mnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopq r s t u v w x y z!{!|"}"~"""""""""""#####$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&'(((())))))))))))************************+++++++++++++,,,,, , , , , ,,,,---------...... .!."/#/$/%/&/'/(/)/*/+/,/-/.///0/1/2/3/4/5/60708090:0;0<0=0>0?0@0A0B0C0D0E0F0G0H0I0J0K0L0M0N0O0P0Q0R0S0T0U0V0W1X1Y1Z1[1\1]1^1_1`1a1b1c1d1e1f1g2h2i2j2k2l2m2n2o2p2q2r2s2t2u2v2w2x2y2z2{2|3}3~3333333333333333333333334444444444444444444444444444444444444444555555555555555555555555555555666666666666666666777777777777777777777777777 7 7 7 7 7777777777778888889 9!9"9#9$9%9&9'9(9)9*9+9,9-9.9/909192939495: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>{>|>}?~?????????????????????@@@@@@@@@@@@AAAAAAAAAAAAAAAAAAAAAABBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD D D D D DDDDDDDDDDDDDDDDDDD D!D"D#D$D%D&D'D(D)D*D+D,D-D.D/D0D1D2D3D4D5D6D7E8E9E:E;E<E=E>E?E@EAEBECEDEEEFEGEHEIEJEKELEMENEOEPEQFRFSFTFUFVFWFXFYFZF[F\F]F^F_F`FaFbGcGdGeGfGgGhGiGjGkGlGmGnGoGpGqGrGsGtGuGvGwGxGyGzG{G|G}G~GHHHHHHHHHIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMM M M M M MMMMMMMMMMMMMMMMMMM M!M"M#M$M%M&M'M(M)M*M+M,M-M.M/M0M1M2M3M4M5M6M7M8M9M:M;M<M=M>M?M@MAMBMCMDMEMFMGMHMIMJMKMLMMMNMOMPMQMRMSMTMUMVMWMXMYMZM[M\M]M^M_M`MaMbMcMdMeMfMgMhMiMjMkMlMmMnMoMpMqMrMsMtMuMvMwNxNyNzN{N|N}N~NNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRRRRRRRRRRRRRRSSSSSSSSSSSSSSSSS S S S S SSSSSSSSSSSTTT T!T"T#T$T%T&T'T(T)T*U+U,U-U.U/U0U1U2U3U4U5U6U7U8U9U:U;U<U=U>U?U@UAUBUCUDUEUFUGUHUIUJUKULUMUNUOUPUQURUSUTUUUVUWUXUYUZU[U\U]U^U_U`UaVbVcVdVeVfVgVhViVjVkVlVmVnVoVpVqVrVsVtVuVvVwVxVyVzV{V|V}V~VVVVVVWWWWWWWWWWWWWWWWWWWWWWWWWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYZZZZZZZZ[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [ [ [ [ [[[a(c) Henning Thielemann 2006$numericprelude@henning-thielemann.de provisional7Routines and abstractions for permutations of Integers. Safe-Inferred%There 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-InferredFzip two lists using an arbitrary function, the shorter list is padded VApply a function to the last element of a list. If the list is empty, nothing changes.padding value 8function applied to corresponding elements of the lists 8function applied to corresponding elements of the lists ] Safe-Inferred(c) Henning Thielemann 2007$numericprelude@henning-thielemann.de provisionalportable Safe-Inferred5Wrap 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.   Safe-Inferred>This class allows defining instances that are exclusively for ; dimension. You won't want to define instances by yourself.U >U H  Safe-Inferred 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.                    ^ Safe-Inferred /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 '(==)'.!It holds 2(a ==? b) eq noteq == if a==b then eq else noteq:for atomic types where the right hand side can be defined. !"#$%&'()*+,-. !"#$ !"#$%&'()*+,-._ Safe-Inferred//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 .0It 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: 0 or '(<=?)'./0123456789:;<=>?@ABCDEFGHIJ/0123456789:;<=>?@/0123456789:;<=>?@ABCDEFGHIJ Safe-Inferred !"#$ !"#$ !"#$ !"#$ Safe-Inferred%  !"#()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~%k 3e",-SR#*./WVUTH)J(012 QPX!`_^]+psq6ul|xzMoE<:;9@NDm baGFnr ?>=K845OL~}tdc[YZ\ vwy{ CAgfIB7jih%% (c) Henning Thielemann 2006$numericprelude@henning-thielemann.de provisional2Permutation represented by an array of the images. Safe-Inferred%/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. &'()*+,-./01 &'()*+,-./01 &'()*+,-./01 &'()*+,-./01  Safe-Inferred% 2[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: 4, 3, and (6 or '(-)')3 zero element of the vector space4add and subtract elements5add and subtract elements6inverse with respect to 477 is (-)q with swapped operand order. This is the operand order which will be needed in most cases of partial application.89Sum up all elements of a list. An empty list yields zero.QThis function is inappropriate for number types like Peano. Maybe we should make 8, a method of Additive. This would also make  lengthLeft and  lengthRight superfluous.9Sum up all elements of a non-empty list. This avoids including a zero which is useful for types where no universal zero is available.:tSum the operands in an order, such that the dependencies are minimized. Does this have a measurably effect on speed?Requires associativity.<qInstead 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.? |addPair :: (Additive.C a, Additive.C b) => (a,b) -> (a,b) -> (a,b) addPair = Elem.run2 $ Elem.with (,) <*>.+ fst <*>.+ snd)23456789:;KL<=>?@ABCDEMNOPQRSTUVWXYZ[\]^_23456789:;<=>?@ABCDE23456789:;<=>?@ACBDE%23456789:;KL<=>?@ABCDEMNOPQRSTUVWXYZ[\]^_45?@A  Safe-Inferred%FWMaybe the naming should be according to Algebra.Unit: Algebra.Zero as module name, and query as method name.HJChecks if a number is the zero element. This test is not possible for all 23 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).FGHIJKLMNOPQRSTUVWXFGHFGHXWVUTSRQPONMLKJIFGHIJKLMNOPQRSTUVWX  Safe-Inferred%YcRing 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: Z, ([ or \)]The 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 ]& with more flexibility is provided by ab.j8Commutativity need not be satisfied by all instances of Y. !YZ[\]^_`abcdefghij`abcdefghijklmnYZ[\]^_`abcdefghijYZ[\]^_`abcdefghijYZ[\]^_`abcdefghij`abcdefghijklmnZ]  Safe-Inferred%klM 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.klklklkl Safe-Inferred%mIntegralDomain* corresponds to a commutative ring, where a o b7 picks a canonical element of the equivalence class of a in the ideal generated by b. n and o 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 n, o, p 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: p or (n and o)s'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]uFReturns the result of the division, if divisible. Otherwise undefined.vFReturns the result of the division, if divisible. Otherwise undefined.w\Allows division by zero. If the divisor is zero, then the dividend is returned as remainder.z 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.$mnopqrstouvwxyz{|}~pqrstuvwxyzmnopqrstuvwxyz{|}~mnopwqruvxy|z{st}~!mnopqrstouvwxyz{|}~pqrstuvwxyzno7(c) Henning Thielemann 2009-2010, Mikael Johansson 2006$numericprelude@henning-thielemann.de provisionalAbstract concept of a Monoid. Safe-InferredfWe expect a monoid to adher to associativity and the identity behaving decently. Nothing more, really.    (c) Henning Thielemann 2007-2010haskell@henning-thielemann.destable Haskell 98 Safe-InferredxInstances 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 { 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. Safe-Inferred%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-Inferred% 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) q x.Like , but aL is minimal with respect to the measure function of the Euclidean algorithm.Not 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-Inferred%Nothing 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-Inferred%246 (c) Henning Thielemann 2004-2005$numericprelude@henning-thielemann.de provisionalportable Safe-Inferred%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.  (c) Mikael Johansson 2006mik@math.uni-jena.de provisional%requires multi-parameter type classes Safe-Inferred%    Safe-Inferred%XThis 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: , .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 Kcz. 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 6$ we could relax the superclasses to Additive and ! if his class would only contain .G(c) Henning Thielemann 2011-2012 (c) Dylan Thurston 2006$numericprelude@henning-thielemann.de provisional portable (?) Safe-Inferred% similar to %d bThis is an alternative show method that is more user-friendly but also potentially more ambigious.ONecessary when mixing NumericPrelude.Numeric Rationals with Prelude98 Rationals    Safe-Inferred%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:  or ()*Needed to work around shortcomings in GHC.)the restriction on the divisor should be isUnit a instead of not (isZero a)  None%YThis class allows lossless conversion from any representation of a rational to the fixed B 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 === id=Lossless conversion from any representation of a rational to It 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.                Safe-Inferred%Remember that p 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 NoneThe 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. !"#$%&'(('&%$#"!  !"#$%&'(None%)Minimal implementation: + or '(^/)'. )*+,-./01234 )*+,-./012 )*+,-.43/012 )*+,-./01234,None%5Transcendental 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)56789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]'56789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[)56789:;<=>?@ABCDEF]\GHIJKLMNOPQRSTUVWXYZ[56789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]:G0(c) Dylan Thurston, Henning Thielemann 2004-2005$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone%246^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_scale a vector by a scalara4Compute the linear combination of a list of vectors.ToDo: Should it use #i ?b(This function can be used to define any 2 as a module over '.Better move to Algebra.Additive?^_`abcdefghijklmnop^_`abcde^_`ponmlkjihgfabcde^_`abcdefghijklmnop_ None%246 qrstuvwxyq qyxwvutsr qrstuvwxy!None%246zLDivisibleSpace is used for free one-dimensional vector spaces. It satisfies  (a </> b) *> b = a(Examples include dollars and kilometers.z{z{z{z{{"$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone%246| 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%lTaken number of elements must be at most the length of the list, otherwise the end of the list is undefined.nDropped number of elements must be at most the length of the list, otherwise the end of the list is undefined.}Split position must be at most the length of the list, otherwise the end of the first list and the second list are undefined.YThe index must be smaller than the length of the list, otherwise the result is undefined.Zip 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.8function applied to corresponding elements of the lists $None%GLeft associative length computation that is appropriate for types like Integer.HRight associative length computation that is appropriate for types like Peano number.    %None%"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  denominator type supports p, every  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%Counterpart of gl$ but with NumericPrelude superclass. 'None%nThis is a convenient class for common types that both form a field and have a notion of ordering by magnitude.(None%VThis class collects all functions for _scalar_ floating point numbers. E.g. computing 7 for complex floating numbers makes certainly no sense.None%R$%&'3456789GZ[\]^_`nopqxy*,6789:;<=>?@ABCDEFG_|454563789GZ[\]^_`nonopqxy,*678789:9:G;<=;<=;<=>?@>?@>?@ABCABCABCDEFDEFDEF'&%$_)None%  mNone  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~%3456789GZ[\]^_`nopqxy*,6789:;<=>?@ABCDEFG_*None%246<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  class.Default definition for  that is based on : class and the argument vector has at least one component.+None%246Default definition for  that is based on  class.Default definition for  that is based on : class and the argument vector has at least one component.   ,None%2463The 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  class.Default definition for  that is based on : class and the argument vector has at least one component.                  -None%246$Remove all zero values from the map.   .None%246 !!  !/2(c) Henning Thielemann 2009, Mikael Johansson 2006$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone%246#8A matrix is a twodimensional array, indexed by integers.$JTransposition of matrices is just transposition in the sense of Data.List.!"#$%&'()*+,-./012345"#$%&'()*+,-./012345#"+$%&'()*,-./012345 "#$%&'()*+,-./0123450(c) Henning Thielemann 2007$numericprelude@henning-thielemann.de provisionalportableNone%6JCons 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.8Unchecked construction.<n`< is not really necessary here and only due to invokation of ;.=n`< is not really necessary here and only due to invokation of .?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.AJThe list of denominators must contain equal elements. Sorry for this hack.CaA normalization step which separates the integer part from the leading fraction of each sub-list.DCf. Number.PositionalEA normalization step which reduces all elements in sub-lists modulo their denominators. Zeros might be the result, that must be remove with F.FRRemove 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 H leads to wrong results.HTransforms a product of two partial fractions into a sum of two fractions. The denominators must be at least relatively prime. Since 6D requires irreducible denominators, these are also relatively prime. Example: mulFrac (1%6) (1%4)% fails because of the common divisor 2.J@Works always but simply puts the product into the last fraction.K`Also works if the operands share a non-trivial divisor. However the results are quite arbitrary.LAExpects an irreducible denominator as associate in standard form.SaApply a function on a specific element if it exists, and another function to the rest of the map.!6789:;<=>?@ABCDEFGHIJKLMNOPQRSTUV6789:;<=>?@ABCDEFGHIJKLMNOPQRS!6789:V;<=>?@ABCDEFGUHIJKLMNOTPQRS 6789:;<=>?@ABCDEFGHIJKLMNOPQRSTUV1(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.acandidates for Utility ?WXYZ[\]^_`abcdefWXYZ[\]^_`abcdefXWYZ[\]^_`abcdefWXYZ[\]^_`abcdef2(c) Henning Thielemann 2006$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone%kWe 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.n5Does not check whether the input values are in range.xTThese instances may need more work They involve converting a permutation to a table.ghijklmnopqrstuvwxyz{ghijklmnopqrstuklmghijnopqrstu{zyxwvghijklmnopqrstuvwxyz{3None%|6Horner's scheme for evaluating a polynomial in a ring.}8Horner's scheme for evaluating a polynomial in a module.9It's also helpful to put a polynomial in canonical form. + strips leading coefficients that are zero.*Multiply by the variable, used internally.7 is fast if the second argument is a short polynomial, 5o relies on that fact.The 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].~Integrates if it is possible to represent the integrated polynomial in the given ring. Otherwise undefined coefficients occur.|}~|}~|}~|}~4None%"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%246"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) 6None%NSince the inner series must start with a zero, the first term is omitted in y.7None% 8Power series of error function (almost). More precisely 1 erf = 2 / sqrt pi * integrate (x -> exp (-x^2)) , with  erf 0 = 0.+     +     +     +     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.tWe 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' * y9None%246}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. !"#$%&'()*+,-./01234 !"#$%&'()*+, !"#$%&'()*+4,3210/.- !"#$%&'()*+,-./01234:None%56789:;<=>?@ABCDEF56789:;<=>?@ABCDEF56789:;<=>?@ABCDEF56789:;<=>?@ABCDEF;(c) Henning Thielemann 2006$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone%Hdenominator conversionI@very efficient because it can make use of the decimal output of _GHIJKLMNOPQRSTUVWXYZ[\]^_`abcdGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdGHIJKLMNOPQRSTUVWXZY[\]^_`abcdGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd<None%iNThe division may be ambiguous. In this case an arbitrary quotient is returned. 0:4 * 2 :4 == 0/:4 2:4 * 2 :4 == 0/:4 efghijkefghijkefghijkefghijk=None%6lmnopqrstuvwxylmnopqrlmnoyxwpqrvuts lmnopqrstuvwxy>None%z{|z{|z{|{ z{|?None%}The 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 pqQ. 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 modulus}~}~}~}~~@None%+Here we try to provide implementations for 3 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 3 and [ can be found ResidueClass.=the modulus can be Nothing to denote a generic constant like 3 and [6 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    ANone%kT is a Reader monad but does not need functional dependencies like that from the Monad Transformer Library.BNone%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.TTest for the neutral Unit.TRConvert a List to sparse Map representation Example: [-1,0,-2] -> [(0,-1),(2,-2)]Convert Map to a ListCNone%A common scaling for a unit.'An entry for a unit and there scalings.,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. ARaise all scales of a unit and the unit itself to the n-th power `Reorder the unit components in a way that the units with positive exponents lead the list. )Decompose a complex unit into common onesMFind the exponent that lead to minimal distance Since the list is infinite G^ will fail but the sequence is convex and thus we can abort when the distance stop falling*;(UnitSet,distance) the UnitSet may contain powered units **DNone%Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Some common quantity classes.Common constants Conversion factorsPhysical constantsPrefixes used for SI units42UnitDatabase.T of units and their common scalings 52UnitDatabase.T of units and their common scalings P      !"#$%&'()*+,-./0123456P      !"#$%&'()*+,-./0123456P     3210/.-,+*)('&%$#"! 456I      !"#$%&'()*+,-./0123456ENoneB7{This 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 Y.&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 Y for all types a that are in Y.789:;<=>?@ABCDEFGHIJKLMNOP789:;<=>789:;<=PONMLKJIHGFEDCBA@?>789:;<=>?@ABCDEFGHIJKLMNOPFNone%246WnHere the coefficients are vectors, for example the coefficients are real and the coefficents are real vectors.XHere the argument is a vector, for example the coefficients are complex numbers or square matrices and the coefficents are reals.YY. is the functional composition of polynomials.It fulfills ' eval x . eval y == eval (compose x y) It 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 m* 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].)QRSTUVWXYZ[\]^_`aQRSTUVWXYZ[\]^_`aQRSRTUZVWX[\Y]^_a`'QRSTUVWXYZ[\]^_`aG (c) Henning Thielemann 2004-2005$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone%246bcdefghijklmnopqrstuvwxyz{|}~bcdefghijklmnopqrstuvwbcdefghijklmnopq~r}st|{zyuxvwbcdefghijklmnopqrstuvwxyz{|}~HNone%$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)  I (c) Henning Thielemann 2004-2005$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone%cf. Fr 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.  JNoneoThe 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))K"(c) The University of Glasgow 2001/BSD-style (see the file libraries/base/LICENSE)$numericprelude@henning-thielemann.de provisional portable (?)None%246We like to build the Complex Algebraic instance on top of the Algebraic instance of the scalar type. This poses no problem to *. However, Ks 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,  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*6). The 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 (-6, 6]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 (-6, 6]1; if the magnitude is zero, then so is the phase. Special implementation of (/)D for floating point numbers which prevent intermediate overflows.  The '(*>)' method can't replace 5 because it requires the Algebra.Module constraint<                            ! " #8                            ! " # L (c) Henning Thielemann 2004-2006$numericprelude@henning-thielemann.de provisional%requires multi-parameter type classesNone%246(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  or with ,  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)  sums this way: | | | ******************************* | | +-------------------------------- | | ************************ | +---------------------------------- | ************ +------------------------------------I.e. K would use much time find the time differences by successive subtraction 1. mixes this way:  +-------------------------------- | ******************************* | +------------------------- | | ************************ | | +------------- | | | ************[Two polynomials may be stored differently. This function checks whether two values of type LaurentPolynomial( actually represent the same polynomial.nCheck whether a Laurent polynomial has only the absolute term, that is, it represents the constant polynomial.p(z) -> p(-z) p(z) -> p(1/z) %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.&&#MNone%-Converts 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.7Eliminate leading zero digits. This will fail for zero. 9Trim until a minimum exponent is reached. Safe for zeros. hAccept a high leading digit for the sake of a reduced exponent. This eliminates one leading digit. Like   but with exponent management. >Merge leading and second digit. This is somehow an inverse of .Make 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.'Split into integer and fractional part.cf. tu^Only return as much digits as are contained in Double. This will speedup further computations. $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 b0BGet the mantissa in such a form that it fits an expected exponent.x and (e, alignMant b e x) represent the same number.73Add 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 wJ, but it pads with zeros if the list is too short. This way it preserves ) length (fst (splitAtPadZero n xs)) == n @help showing series summandsEFor 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 A and <. We should fix that.FUndefined 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.J`Fast division for small integral divisors, which occur for instance in summands of power series.P 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 .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) ?RuNewton 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.SList.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 vw 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.undefinedU-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.aLike ` 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.g 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.jThis is an inverse of b, also known as atan2v 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.k9Arcus tangens of arguments with absolute value less than  1 / sqrt 3.mBEfficient computation of Arcus tangens of an argument of the form 1/n.njThis implementation gets the first decimal place for free by calling the arcus tangens implementation for $s.o!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.      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuv      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuv      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuv      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvN$numericprelude@henning-thielemann.de provisional portable (?)None%246wQuaternions could be defined based on Complex numbers. However quaternions are often considered as real part and three imaginary parts.x real partyimaginary parts{4Construct 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 dependency~Fthe 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 constraint"w 'xyz ({|} %~ )For 0 return vector v, for 1 return vector w vector v, must be normalized vector w, must be normalized * & + , - . / 0 1 2 3wxyz{|}~wxyz{|}~w 'xyz ({|} %~ ) * & + , - . / 0 1 2 3 '{xNone246 4A special reader monad. 5The 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. 6Infix variant of  7. 4 8 9 : ; 5 7 6 < = > ? @ A B C D E F G H I J 4 8 9 : ; 5 7 6 < = > ? @ 4 8 9 : ; 5 7 6 < = > ? @ A B C D E F G H I J 6ONone%iHere 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.PNone6B|This makes a type usable with Haskell98 type classes that was initially implemented for NumericPrelude typeclasses. E.g. if a is in class Y, then T a is both in class { and in Y.&You can even lift container types. If  Polynomial a is in Y for all types a that are in Y, then .T (Polynomial (MathObj.Wrapper.Haskell98.T a)) is in { for all types a that are in {.QNone2460(0/RNone%( !"#$%&'()*+,-./0123( !"#$%&'()*+,-./0123SNone%denominator conversion                  (c) Henning Thielemann 2007haskell@henning-thielemann.destable Haskell 98None%]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. K'Results are not checked for positivity. L'Results are not checked for positivity.=name of the calling function to be used in the error message M K N L O P Q R S T U V W X Y Z [ \   M K N L O P Q R S T U V W X Y Z [ \T (c) Henning Thielemann 2007-2010haskell@henning-thielemann.destable Haskell 98NoneA 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 yz.$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. ]p 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.0 ^ _ !"# `$ 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 { | } ~ U (c) Henning Thielemann 2007-2012$numericprelude@henning-thielemann.de provisionalportableNone%93If 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.CIn 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.ChunkyF"Compute '(&&)' with minimal costs.7*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`!*+,-./0123456789:;<=>?@ABCDEFGHIJ7.0/12`345678_^]9\[Z:;<=>?@ABCD*+,-EFGHIYXWVUTSRQPONJMLK2*+,-.0/123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`FVNone%a 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.f|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.g7perfect carry resolution, works only on finite numbers #abcdefghijklmnopqrstuvwxyz{|}~abcdefghijklmnopqr#abcdefghijklmnopqr~}|{zyxwvutsabcdefghijklmnopqrstuvwxyz{|}~WNone%246A 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. XNone%246IA 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!! YNone%`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    ZNone%lThis function could also return the value, but a list of pairs (String, Integer) is easier for testing. [None%246B@     /@     ?      {|}{~{|{{{{{{{|{|{|{~j{{{{{|{|{|{|{|{{{{|{|{{{{|{{{g{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{i{{{{{{{{{{{{{{{{ { { { { {{{{{{{{{{{{{{{{{{ {!{"{|#{|${|%{|&{|'{|()*+,-./0123453463473434343489:`;<=>?`*@ABCDDEFFGGHHIIJJKKLLMNOPQQRRSS`TUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~7= 7       =     `                    `                   `                  ` `h```     ` !"#$%&'()*+,,-../0012234567`89`:;<=>?@7iABCDEF`GHIJK7LMNOPQXRS`TXUVWXY`Z[`\]^`_`baD`bscdef`ghijoklmnopqrstuvwxyz{|}~`;=> `        !`!"`""""""""""""# ####i$ $ $$$$$$$$%`%d%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%D&`&&&&&&&&P&&&&&&&'`(`((()`)))))))))1)2)G*`**P*********************+`++++++++++++,`,,,,,,,,,,,,---------.`.N..O....//7////////////i////P//070000U00000000O0 0 0 0 0i0 000000W000000D0E0C171111111;1111 11!1"1=27222#222 22$2%2&2'2(2)22D2*2+2C2,2E3-3.3/3031323333433P3536373W383933:33;33<3=3r3>4?4@4A4B4C4D4>4E4F4G44444P4W4H44I4J4;4K44<4b4L4h4M4N4k4m4l4i4O4o4n4p44P4Q4R5755S5T5U5V5W5'5U55?5@5A5B5C5D55D5E5F5X5Y5Z5[5\5]5^5+5C5676_6`6a66466P6W6I6b6L6b6c6d6e6f67X7h7k7m7l7i7n7p7o7q7s7u7L7b7g7h7i7j7k7l7m7n7o7p7q7r7s7t7u7v7w7x7y7z7{7|7}7~777778888889799S999T999U9V9W9'99U9D9E9F9X9Y9+9C9::::::::::::::::::;;;;;;;;;;4;W;I;X;;b;s;;m;k;l;;;;;;;h;;;<<4<<W<<I<X=7===U={=W===D=E=F===C>7>>O?7?????????V?W?'????D?E?F?X?+??C@7@@@@@@@@W@D@E@+A7AAAAAAAAAAAAAAAAAAAAAB7BVBBBBBBCCCCcCCCCCCCCCCCCCCCCCCC7CCCCCCCCCCCCCCCCCCCDDFDGDHDIDJDKDLDDDDDjDpDDDkDDDDeDlDDqDDDmD DnDoD D D D DDDDDDDDDDDDDDDDDDD D!D"D#D$D%D&D'D(D)D*D+D,D-DD.D/D0D1D2D3D4D5D6D7D8D9D:E7EEEVEWE;E<E=EDEEEFEXEYE\E]E^E>E?E@EAEBECEDEEEFEF7FSFTFGFHF?F@FAFF'F5F<FIFFJFKFLG7GGMGUGVGWG'GNGOGPGQGRGSGTGUGUGGWGLGsGVGWGDGEGZG[GFGXGCH7HSHTHSHXHYHZH[H\I7IISIUIVIWI'IXISI]I^I_III`IaIbIcIdIeIUIIfIWIgILIhIiIDIEIFIXICJ7JJjJ5JkJlJWJhJXJmJnJoJsJbJ*J+JKpKeK7KqKrKsKtKuKvKwKPKhKxKyKHKzK{K|K}KcK~KKKL7LLLSL'LLTLLSLLL1LJLULLLLLL4LWLhLLLLL>LLL+LDLELZL[LFLXLCLMMMMMMM7MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM4MMMMMMMMMPMMMMWMIMMMMMMMbMMMMMMMMMMMhMMMMMeMsMMMMMlMMMMMMMmMMMMMMMMMMMMN7NqNrNtNNwNPNNN0NNNNNNNNNO7OOOOUOVOWOOOO3OOOOCO+OODOEOFOXP7PPPVPWP=PPPPPPPPPP P P P P PPQDQEQFQGQHQIQJQKQLQSQ7QQjQ5QQQQQQQQXQQQbQGQQPQQQVQQjQkQlQpQmQnQoQqQQZQDQEQ[QFQQCRRRRRR R!R"R#R$R%R&R'R(R)R*R+R,R-S7SSNSMS.SS/SUS0S1S2SSUSVSWS3SUS4S5S SSDSES*S+SFSXSYS\S]S^SCK6j78T7T9T:T;T<TjT5T0T=T>T?T@TAUBUBUCUDU7UEUFUGUHUU4UIUWUJUKUULUMUNUOUPUQURUSUTUUUVUWUXUYUZU[UU U UU\UDUEUFU]UXUYU\U]U^U>U?U*U@UAU^UBUCUDV7VV{VV_VV`VVUVVVWVaVVVbVcVdV5V VVeVDVEVFVXV*V+VYV\V]V^V>V?V@VAWfWgWRWhWiW7WWOWjWkWlWOWmWnWZWDWEWFWXWYW\W]W*W+WCX7XXoXpXXlXWXqXrXsXtXuXPXvXwXxXXXXZX[XyXDXEXFXXXYX*X\X]XCX+X^YzY{Y|Y}Y~YYYYYZzZZZZZZZ[[7[[l[W[[r[P[p[{[[o[ [[[[[[![["[#[[[[[[$[[%[[[&['[([[)[*[+[,[-[[[ [!["[#[ [[Z[[[y[D[E[F[X[Y[*[\[][[C[+[^\\\\\\]]]]]>^`^^^^^@^^^^^^^^^_`_*_____1_2___________@_________     @                               {VW CDE*FXYD#'D'')))D){//U//////Z/D//E/F/C>>U>V>W> >>D>E>F>X>YFFXFFUFVFWFFUF FFFDFEFFFYFZF[F\F]F^F>F+FCFHHUHUHHHHHCHKKKKKKKKKIK KKDKEKKKFKXKYK\KZK[KyKKKK]K^K>K?K@KAKKKKKC{wNN[NNNNZNDNENFNXNYNyNNNCxx`xxxxxFxxxxxxxxxxZxxxxxxlWDEFXY\]^>?@ABCTETTTWTTTTTUTTTTTTTTTTTDTT TTTCTFTXTYT\T]T^T>T?T*T+numeric-prelude-0.4.2NumericPrelude.BaseNumericPrelude.NumericNumber.NonNegativeMathObj.PermutationAlgebra.IndexableAlgebra.DimensionTermNumericPrelude.Elementwise Algebra.LawsMathObj.Permutation.TableAlgebra.AdditiveAlgebra.ZeroTestable Algebra.RingAlgebra.DifferentialAlgebra.IntegralDomainAlgebra.MonoidAlgebra.NonNegative Algebra.UnitsAlgebra.PrincipalIdealDomainMathObj.MonoidAlgebra.RightModuleAlgebra.VectorMathObj.AlgebraAlgebra.Absolute Number.Ratio Algebra.FieldAlgebra.ToRationalAlgebra.RealIntegralAlgebra.ToIntegerAlgebra.AlgebraicAlgebra.TranscendentalAlgebra.ModuleAlgebra.VectorSpaceAlgebra.DivisibleSpaceAlgebra.ModuleBasisNumericPrelude.List.CheckedNumericPrelude.List.GenericAlgebra.RealRingAlgebra.FloatingPointAlgebra.RealFieldAlgebra.RealTranscendentalAlgebra.LatticeAlgebra.NormedSpace.EuclideanAlgebra.NormedSpace.MaximumAlgebra.NormedSpace.SumMathObj.DiscreteMapAlgebra.OccasionallyScalarMathObj.MatrixMathObj.PartialFractionMathObj.Permutation.CycleList#MathObj.Permutation.CycleList.CheckMathObj.Polynomial.CoreMathObj.PowerSeries.CoreMathObj.PowerSeriesMathObj.PowerSeries2.CoreMathObj.PowerSeries.Example(MathObj.PowerSeries.DifferentialEquationMathObj.PowerSeries2MathObj.PowerSeries.MeanNumber.FixedPointNumber.ResidueClassNumber.GaloisField2p32m5Number.PartiallyTranscendentalNumber.ResidueClass.CheckNumber.ResidueClass.MaybeNumber.ResidueClass.ReaderNumber.Physical.UnitNumber.Physical.UnitDatabaseNumber.SI.UnitMathObj.Wrapper.Haskell98MathObj.PolynomialMathObj.PowerSumMathObj.RefinementMask2MathObj.RootSet Number.RootNumber.ComplexMathObj.LaurentPolynomialNumber.PositionalNumber.QuaternionNumber.ResidueClass.FuncMathObj.Wrapper.NumericPreludeNumber.DimensionTermNumber.DimensionTerm.SINumber.FixedPoint.CheckNumber.NonNegativeChunky Number.PeanoNumber.Positional.Check#Number.OccasionallyScalarExpressionNumber.PhysicalNumber.Physical.ShowNumber.Physical.Read Number.SINumericPrelude.ListAlgebra.RealRing98Algebra.EqualityDecisionAlgebra.OrderDecisionC Algebra.Core ringPower magnitude splitFractionAlgebraTranscendentalPreludedivzipWith undefinedproperFraction RealFloatNumericPreludePrincipalIdealDomain**Control.Monad.STrunSTmulLinearFactorrootNumeric floatToDigits Data.List.HTinitsAlgebra.AffineSpaceNumeric.NonNegativeChunkybaseGHC.Base++GHC.Errerrorfoldrghc-primGHC.PrimseqGHC.Listconcatfilterzip System.IOprint Data.Tuplefstsnd otherwisemap$GHC.EnumenumFrom enumFromThen enumFromToenumFromThenTo GHC.Classes==>=fail>>=>>fmapreturnGHC.Real realToFracBoundedEnumEqMonadFunctorOrdGHC.ReadReadGHC.ShowShow GHC.TypesBoolCharDoubleFloatInt integer-gmpGHC.Integer.TypeIntegerOrderingIO Data.EitherEitherStringFalseTrueLeftRightLTEQGT$!readIOreadLn appendFile writeFilereadFileinteract getContentsgetLinegetCharputStrLnputStrputCharGHC.IO.ExceptionioError Data.Listunwordswordsunlineslinesfoldl1minimummaximumGHC.IOFilePath userErrorIOError Text.Readreadreadseitherlex readParenreadList readsPrecmaxBoundminBoundfromEnumtoEnumpredsuccText.ParserCombinators.ReadPReadS showParen showStringshowCharshowsShowSshowListshow showsPrec Control.MonadmapM_mapM sequence_sequence=<<unzip3unzipzipWith3zip3!! concatMaplookupnotElemelemallanyorandreversebreakspansplitAtdroptake dropWhile takeWhilecycle replicaterepeatiteratescanr1scanrfoldr1scanl1scanlfoldllengthnullinitlasttailhead Data.MaybemaybeNothingJustMaybeuncurrycurryasTypeOfuntilflip.constid/=compare<=&&||not<>maxminnon-negative-0.1.1Numeric.NonNegative.WrappertoNumberfromNumberUnsafeTutility-ht-0.0.10Data.Bool.HT.Private ifThenElsedomainapplyinverseToOrdfromOrd ordCompare liftComparetoOrdVoltageAnalyticalVoltage Frequency Information TemperatureAngleChargeMassTimeLengthIsScalartoScalar fromScalarSqrRecipMulScalarnoValueappPrecscalarmulrecip%*%%/% applyLeftMul applyRightMul applyRecipcommute associateLeftassociateRightrecipMulmulRecip identityLeft identityRight cancelLeft cancelRight invertRecip doubleRecip recipScalartimemasschargeangle temperature information frequencyvoltage unpackVoltage packVoltage $fCVoltage $fShowVoltage$fCInformation$fCTemperature$fCAngle $fCCharge$fCMass$fCTime $fCLength$fShowInformation$fShowTemperature $fShowAngle $fShowCharge $fShowMass $fShowTime $fShowLength$fIsScalarScalar$fCRecip$fCMul $fCScalar $fShowRecip $fShowMul $fShowScalarConsrunwithelementrun2run3run4run5$fApplicativeT $fFunctorT commutative associative leftIdentity rightIdentityidentityleftZero rightZerozero leftInverse rightInverseleftDistributiverightDistributive homomorphism rightCascade leftCascadecatch fromFunction toFunctionfromPermutation fromCyclescomposechooseclosure closureSlow+-negatesubtractsumsum1sumNestedAssociativesumNestedCommutative elementAdd elementSub elementNeg<*>.+<*>.-<*>.-$propCommutativepropAssociative propIdentity propInverseisZero defltIsZero$fC[]$fC(,,)$fC(,) $fCWord64 $fCWord32 $fCWord16$fCWord8$fCWord$fCInt64$fCInt32$fCInt16$fCInt8$fCInt $fCDouble$fCFloat $fCInteger*one fromInteger^sqrproductproduct1 scalarProductpropLeftDistributivepropRightDistributivepropLeftIdentitypropRightIdentitypropPowerCascadepropPowerProductpropPowerDistributive differentiatemoddivModdividessameResidueClassdecomposeVarPositionaldecomposeVarPositionalInf divCheckedsafeDiv divModZeroevenodd roundDownroundUpdivUppropMultipleDivpropMultipleModpropProjectAdditionpropProjectMultiplicationpropUniqueRepresentativepropZeroRepresentativepropSameResidueClassidt<*>cumulate$fCSum $fCProduct$fCLast$fCFirst$fCEndo$fCDual$fCAny$fCAllsplit splitDefaultadd-|isUnit stdAssociate stdUnitInvstdUnitintQuery intAssociate intStandardintStandardInversepropCompositionpropInverseUnitpropUniqueAssociatepropAssociateProduct extendedGCDgcdlcmcoprimeeuclidextendedEuclidextendedGCDMulti diophantinediophantineMindiophantineMultichineseRemainderchineseRemainderMultipropMaximalDivisorpropGCDDiophantinepropExtendedGCDMultipropDiophantinepropDiophantineMinpropDiophantineMultipropDiophantineMultiMinpropDivisibleGCDpropDivisibleLCMpropGCDIdentitypropGCDCommutativepropGCDAssociativepropGCDHomogeneous propGCD_LCMpropChineseRemainderMaxrunMaxMinrunMinLCMrunLCMGCDrunGCD$fCMax$fCMin$fCLCM$fCGCD<*eq<+>*> functorScale linearComb propCascade$fEq[]$fC(->) mulMonomialmonomial$fShowT$fCT$fCT0$fCT1abssignumabsOrd signumOrdRational:% numerator denominator fromValuescale% showsPrecAuto toRational98/ fromRational'^- fromRational propDivisionpropReciprocal toRational realToFieldquotremquotRem toInteger fromIntegral fieldPowersqrt^/ genericRootpower propSqrSqrtpiexploglogBasesintancosasinatanacossinhtanhcoshasinhatanhacosh^? propExpLog propLogExp propExpNeg propLogRecippropExpProductpropExpLogPower propLogSumpropTrigonometricPythagoras propSinPeriod propCosPeriod propTanPeriodpropSinAngleSumpropCosAngleSumpropSinDoubleAnglepropCosDoubleAngle propSinSquare propCosSquare<*>.*>integerMultiply $fCaComplex$fCa(->)$fCa[]$fCa(,,)$fCa(,) $fCIntegerT$fCTT$fCIntegerInteger $fCIntInt$fCDoubleDouble $fCFloatFloatbasisflatten dimension propFlatten propDimension lengthLeft lengthRight elemIndex elemIndices findIndex findIndicesfractionceilingfloortruncateround roundSimplefastSplitFractionfixSplitFraction fixFractionsplitFractionIntfloorInt ceilingIntroundIntroundSimpleIntapproxRational powersOfTwopairsOfPowersOfTwo genericFloorgenericCeilinggenericTruncate genericRoundgenericFractiongenericSplitFractiongenericPosFloorgenericPosCeilinggenericHalfPosFloorDigitsgenericPosRoundgenericPosFractiongenericPosSplitFractiondecisionPosFractiondecisionPosFractionSqrTimeradixdigitsrangedecodeencodeexponent significandisNaN isInfiniteisDenormalizedisNegativeZeroisIEEEatan2updnpropUpCommutativepropDnCommutativepropUpAssociativepropDnAssociativepropUpDnDistributivepropDnUpDistributivenormnormSqrnormSqrFoldablenormSqrFoldable1 defltNorm $fSqraComplex$fSqra[] $fSqra(,,) $fSqra(,)$fSqrTT$fSqrIntegerInteger $fSqrIntInt$fSqrDoubleDouble$fSqrFloatFloat normFoldable normFoldable1strip$fCaMap$fCaMap0 $fSqraMap$fCaMap1$fCaMap2$fCaMap3$fCMap$fCMap0 toMaybeScalartoScalarDefault toScalarShow Dimension transposerowscolumnsindexfromRows fromColumnsfromListformatnumRows numColumnsdiagonalrandomrandomRfromFractionSum toFractionSum toFractiontoFactoredFractionmultiToFraction hornerRevfromFactoredFractionfromFactoredFractionAltmultiFromFraction reduceHeads carryRipplenormalizeModulo removeZerosmulFracmulFrac' mulFracStupidmulFracOverlap scaleFracscaleIntmulFastindexMapMapWithKeyindexMapToListindexMapFromList mapApplySplitCyclecycleRightActioncycleLeftAction cycleAction cycleOrbit cyclesOrbitorbittakeUntilRepetitiontakeUntilRepetitionSlowkeepEssentials isEssentialcyclestoCyclestoTable fromTable errIncompat liftCmpTable2 liftTable2$fOrdT$fEqT $fShowCyclehornerhornerCoeffVectorhornerArgVector normalizeshiftunShiftequalsub collinear tensorProducttensorProductAltmulShearmulShearTranspose divModRev progression integrate integrateInt alternateevaluateevaluateCoeffVectorevaluateArgVector approximateapproximateCoeffVectorapproximateArgVectorholes2holes2alternate insertHoles stripLeadZerodividedivideStripZerorecipProgressionpowsinCos sinCosScalar derivedLog composeTaylorinvinvDiffcoeffs fromCoeffslift0lift1lift2$fCT2$fCT3$fCaT$fCaT0$fCT4$fCT5$fCT6lift0fromPowerSerieslift1fromPowerSerieslift2fromPowerSeries swapVariablesdifferentiate0differentiate1 integrate0 integrate1 recipExplexpExplsinExplcosExpltanExpl tanExplSievelogExplatanExplsinhExplcoshExpl atanhExplpowExplsqrtExplerfexpODEsinODEcosODEtanODE tanODESievelogODE recipCircleasinODEatanODEsqrtODEacosODEsinhODEcoshODEatanhODEpowODE solveDiffEq0 verifyDiffEq0 propDiffEq0 solveDiffEq1 verifyDiffEq1 propDiffEq1isValidcheckfromPowerSeries0fromPowerSeries1diffComp logarithmic elemSym3_2 quadratic quadraticMVF quadraticDiff quadratic2quadraticDiff2 harmonicMVF harmonic2 harmonicDiff2 arithmeticMVF arithmetic2arithmeticDiff2 geometricMVF geometric2geometricDiff2meanValueDiff2 fromFloatfromFixedPointshowPositionalDecshowPositionalHexshowPositionalBinshowPositionalBasisliftShowPosToInt toPositional magnitudesevalPowerSeries arctanSmallarctanpiConstexpSmalleConst recipEConst approxLogBaselnSmalllnneg divideMaybedecons lift2Integer $fStorableT $fArbitraryTtoValuemodulusrepresentative factorPrec/: isCompatiblemaybeCompatiblefromRepresentative$fReadT matchMaybeisCompatibleMaybetoFuncconcretegetZerogetOnegetAddgetSubgetNeggetAdditiveVarsgetMul getRingVars getDividegetRecip getFieldVars monadExample runExample$fMonadTisScalar fromVectortoVectorratScale ratScaleMayberatScaleMaybe2ScalesymbolUnitSetunit independent defScaleIx reciprocalscales InitScale initSymbolinitMag initIsUnit initDefault InitUnitSetinitUnitinitIndependent initScales extractOne initScale initUnitSet createScale createUnitSet showableUnitpowerOfUnitSet powerOfScaleshowExppositiveToFront decompose findIndep findClosestevalDist findBestExp findMinExpdistLE distances listMultiplesdistanceareavolumespeed accelerationforcepressureenergycurrent resistance capacitance angularSpeeddataRatepercentfourthhalf threeFourthsecondsPerMinutesecondsPerHour secondsPerDaysecondsPerYear meterPerInch meterPerFoot meterPerYardmeterPerAstronomicUnitmeterPerParseck2deg180grad200 radPerDeg radPerGradbytesizeaccelerationOfEarthGravitymach speedOfLight electronVoltcalorien horsePoweryoctozeptoattofemtopiconanomicromillicentidecidecahectokilomegagigaterapetaexazettayotta databaseRead databaseShowdatabaseunliftF1unliftF2 unimplemented$fCT7$fCT8$fCT9$fCT10$fCT11$fCT12$fCT13$fCT14$fCT15degreeshowsExpressionPrec fromRoots translateshrinkdilatesums fromElemSym divOneFlipfromElemSymDenormalized toElemSym toElemSymIntfromPolynomialelemSymFromPolynomial binomials approxSeriespropOp toPolynomialtoPolynomialFastrefinePolynomialconvolvePolynomial!convolveTruncatedPowerPolynomials toPowerSums fromPowerSumsaddRootliftPowerSum1GenliftPowerSum2Gen liftPowerSum1 liftPowerSum2liftPowerSumInt1liftPowerSumInt2addIntmulIntpowIntapproxPolynomial fromNumber toRootSet commonDegree cardinalPower integerPower rationalPowerPowerrealimag imaginaryUnitfromReal+:-: conjugate quarterRight quarterLeft signumNorm fromPolarcis propPolar magnitudeSqrphasetoPolardefltPowexpon!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 equalApproxifLazymean2withTwoMantissasalign alignMantabsoluteabsMant fromLaurent toLaurent liftLaurent2liftLaurentManyaddSomeaddMany seriesPlainsplitAtPadZerosplitAtMatchPadZerotruncSeriesSummands scaleSimple scaleMant mulSeriesdivMant divMantSlow divIntMant divIntMantInfdivInt sqrtDriversqrtMantsqrtFP sqrtNewton sqrtFPNewton lazyInits expSeries expSeriesLazy expSmallLazyintPower cardPower powerSeries powerSmall cosSinhSmall cosSinSmall cosSinFourthcosSincotlnSerieslnNewton lnNewton' arctanSeries arctanStem arctanClassicminusOne sliceVertPair+:: crossProduct similaritytoRotationMatrixfromRotationMatrixfromRotationMatrixDenormtoComplexMatrixfromComplexMatrixslerpnotImplementedlift98_1lift98_2$fNumT$fCTT0$fCTT1$fCTT2$fCTT3$fCTT4$fCTT5 $fRealFloatT $fRealFracT$fRealT $fFloatingT $fFractionalT $fIntegralTfromNumberWithDimensiontoNumberWithDimension&*&&/& mulToScalar divToScalarcancelToScalarunrecip absSignum*&rewriteDimension $fRandomT $fNFDataTsecondminutehourdayyearhertzmetergrammtonnecoulombvoltkelvinbitbyteinchfootyardastronomicUnitparseccons fromInteger'fromFloatBasisfromIntegerBasisfromRationalBasiscommonDenominatordefltDenominator defltShowRatio fromNumberMsgfromNumberClip fromChunkstoChunks fromChunky98 toChunky98isNull isPositive minMaxDiff divModLazy divModStrictValuablecostsvalueSuccZeroinfinityerrsubNeg fromPosEnum toPosEnum argMinFullargMin argMinimum argMaxFullargMax argMaximumisAscendingFiniteListisAscendingFiniteNumbers toListMaybeglue isAscending increaseCosts&&~andWleW isAscendingW $fBoundedT$fIxT$fEnumTmantissacarry commonBasis defltBaseRoot defltBaseExp defltBase$fPowerTTermDivAddConstmakeLine showUnitErrorlift scalarMap scalarMap2quantityfromScalarSingle lift2Maybelift2GenerrorUnitMismatchaddMaybesubMayberatPow ratPowMaybe fromRatio$fCaT1mulPrecshowNat showSplit showScaled chooseScale showUnitPartdefScalefindCloseScale totalDefScalegetUnitreadsNat readUnitPart parseProductparseProductTail parsePower ignoreSpace createDictPValueliftGenliternewtonpascalbarjoulewattampereohmfaradbaud zipWithPadmapLastzipWithOverlapzipWithCheckedmapLast' mapLast'' fastFractionsignedFraction $fOrdToOrd==?deflt<*>.==? $fCOrdering$fCBool<=?>=?? compareOrdelementCompare<*>.<=>?<*>.<=?<*>.>=?<*>..>?_sumNestedCommutativesum2 $fCComplex$fCRatiodecomposeVarPositionalInfAuxGHC.NumNumdiophantineMultiMinminimizeFirstOperanddiophantineAuxpropDiophantineGenpropDiophantineMultiGen ratioPrecliftOrdstore randomR01fromRational98 moduleError Data.FoldableFoldableformatS randomAux indexRange indexBounds allIndicesplusPrecpolynomialDifferencecorrectConstantconvolvefloatMagnitude floatDivide$fCaT4 divModCentmodCent $fPowerDouble $fPowerFloat$fSqraT$fCaT2$fCaT3 scaleImag checkBoundsMAC*.+multiplyAccumulaterunMacmultiplyAccumulateModulemakeMacmakeMac2makeMac3$fApplicativeMAC $fFunctorMAC$fZeroT$fZeroT0 $fZeroDouble $fZeroFloatfromNumberWrapliftWrap isNullList isNullListZTisNullZT equalList compareListminListmaxList fromChunky98_ toChunky98_ fromNumber_ $fMonoidT