dK      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmn o p q r s t u v w x y z { | } ~        !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklm n!o!p"q"r"s"t"u"v#w#x#y#z#{$|$}$~$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&'(())))))))))))*******++++,,,,-......////////////////////0000000000000000000000000000 0 0 1 1 1111111111111122222 2!2"2#2$2%2&2'2(2)2*3+3,3-3.3/303132333435363738393:3;3<3=3>3?3@3A3B3C3D4E4F4G4H4I4J4K4L4M4N4O4P4Q4R4S4T4U4V4W4X4Y4Z4[4\4]4^4_4`4a4b4c4d4e4f4g4h4i4j5k5l5m5n5o5p5q5r5s5t5u5v5w5x5y5z5{6|6}6~6666666666666677777777777777777777777777777777777777777778888889999999999999::::::::::::::::::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<<<<<<<=======> > > > > >>>>>>>>>>????????? @!@"@#@$@%@&@'@(@)@*@+@,@-@.@/@0@1@2@3A4A5A6A7A8A9A:A;B<B=B>B?B@BABBBCBDBEBFBGBHBIBJBKBLBMBNBOBPBQBRBSBTBUBVBWBXBYBZB[B\B]B^B_B`BaBbBcBdBeCfCgChCiCjCkClCmCnCoCpCqCrCsCtCuCvCwCxCyCzC{C|C}C~CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHI I I I I IIIIIIIIIJJJJJJJJJJ J!J"J#J$J%J&J'J(J)J*J+J,J-J.K/K0K1K2K3K4K5K6K7K8K9K:K;K<K=K>K?K@KAKBKCKDKEKFKGKHKIKJKKLLLMLNLOLPLQLRLSLTLULVLWLXLYLZL[L\L]L^L_L`LaLbLcLdLeLfLgLhLiLjLkLlLmLnLoLpLqLrLsLtLuLvLwLxLyLzL{L|L}L~LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMNNNOOOOOOOOOOOOOOPPPPPPQQQQQQQQQQQQQQQQQQQQ Q Q Q Q QQQQQQQQQQQQQQQQRRR R!R"R#R$R%R&R'R(R)R*R+R,R-R.R/R0S1S2S3S4S5S6S7S8S9S:S;S<S=S>S?S@SASBSCDEFGHTITJTKTLTMTNTOTPTQTRTSTTTUUVUWUXUYUZU[U\U]U^U_U`UaUbUcUdUeUfUgUhUiUjUkUlUmUnUoUpUqUrUsUtUuUvVwVxVyVzV{V|V}V~VVVVVVVVVVWWWWWWWWWWWWWWXXXXXXXXXXXXXXXXYYYYYYYYYYZZZZZZZZ[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[e7Routines and abstractions for permutations of Integers. provisional$numericprelude@henning-thielemann.de Safe-Inferred EThere are quite a few way we could represent elements of permutation Fgroups: 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-InferredGzip two lists using an arbitrary function, the shorter list is padded 0Apply a function to the last element of a list. 'If the list is empty, nothing changes. padding value 9function applied to corresponding elements of the lists 9function applied to corresponding elements of the lists ] Safe-Inferredportable provisional$numericprelude@henning-thielemann.de Safe-Inferred5Wrap an indexable object such that it can be used in Data.Map and Data.Set. 1Definition of an alternative ordering of objects (independent from a notion of magnitude. For an application see MathObj.PartialFraction. If the type has already an  instance +it is certainly the most easiest to define  to be equal to Ord's . Lift ' implementation from a wrapped object.  portable provisional$numericprelude@henning-thielemann.de Safe-Inferred)>This class allows defining instances that are exclusively for 1 dimension. You won'(t want to define instances by yourself. U !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRST     > !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRST>3412/0-.,56789:;<=>?@ABCDEFGHI)*+'(%&#$!" JKLMNOPQRSTH !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRST      Safe-InferredU'A reader monad for the special purpose Cof defining instances of certain operations on tuples and records. BIt does not add any new functionality to the common Reader monad, 4but it restricts the functions to the required ones "and exports them from one module. "That is you do not have to import 9both Control.Monad.Trans.Reader and Control.Applicative. AThe type also tells the user, for what the Reader monad is used. EWe can more easily replace or extend the implementation when needed. UVWXYZ[\] UVWXYZ[\] UVWXYZ[\] UVWXYZ[\]^ Safe-Inferred/For atomic types this could be a superclass of . 9However for composed types like tuples, lists, functions we do elementwise comparison @which is incompatible with the complete comparison performed by '(==)'.  It holds  4 (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 . 9However for composed types like tuples, lists, functions we do elementwise comparison @which is incompatible with the complete comparison performed by ". # It holds   (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:  # or '(<=?)'. !#$%&'()*+,-./0123456789:;<=!#$%&'()*+,-./0123!#$%&'()*+,-./0123456789:;<= Safe-Inferred^_`abcdefghijklm^_`abcdefghijklm^_`abcdefghijklm^_`abcdefghijklm Safe-Inferred>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"  2Permutation represented by an array of the images. provisional$numericprelude@henning-thielemann.de Safe-InferredwExtremely 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. nopqrstuvwxy nopqrstuvwxy nopqrstuvwxy nopqrstuvwxy  Safe-Inferred zEAdditive a encapsulates the notion of a commutative group, specified by the following laws:    a + b === b + a  (a + b) + c === a + (b + c)  zero + a === a  a + negate a === 0 9Typical 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 (-) with swapped operand order. =This is the operand order which will be needed in most cases of partial application. Sum up all elements of a list. An empty list yields zero. <This function is inappropriate for number types like Peano. Maybe we should make  a method of Additive. This would also make  lengthLeft and  lengthRight superfluous. )Sum up all elements of a non-empty list. 7This avoids including a zero which is useful for types &where no universal zero is available. Sum the operands in an order, *such that the dependencies are minimized. -Does this have a measurably effect on speed? Requires associativity. ?Instead of baking the add operation into the element function, we could use higher rank types and pass a generic  uncurry (+) to the run function. ,We do not do so in order to stay Haskell 98 &at least for parts of NumericPrelude. D addPair :: (Additive.C a, Additive.C b) => (a,b) -> (a,b) -> (a,b) ; addPair = Elem.run2 $ Elem.with (,) <*>.+ fst <*>.+ snd )z{|}~z{|}~z{|}~%z{|}~  Safe-Inferred6Maybe the naming should be according to Algebra.Unit: !Algebra.Zero as module name, and query as method name. (Checks if a number is the zero element. "This test is not possible for all z types, 2since e.g. a function type does not belong to Eq. 7isZero is possible for some types where (==zero) fails !because there is no unique zero.  Examples are 3vector (the length of the zero vector is unknown), :physical values (the unit of a zero quantity is unknown), (residue class (the modulus is unknown).  None-Ring encapsulates the mathematical structure 7of a (not necessarily commutative) ring, with the laws    a * (b * c) === (a * b) * c  one * a === a  a * one === a  a * (b + c) === a * b + a * c KTypical examples include integers, polynomials, matrices, and quaternions. Minimal definition: , ( or ) The exponent has fixed type  in order 9 to avoid an arbitrarily limitted range of exponents, N but to reduce the need for the compiler to guess the type (default type). H In practice the exponent is most oftenly fixed, and is most oftenly 2. . Fixed exponents can be optimized away and & thus the expensive computation of s doesn' t matter. ! The previous solution used a ` constrained type B and the exponent was converted to Integer before computation. 3 So the current solution is not less efficient.  A variant of & with more flexibility is provided by ab. 8Commutativity need not be satisfied by all instances of . !        None' is a general differentation operation 'It must fulfill the Leibnitz condition  F differentiate (x * y) == differentiate x * y + x * differentiate y QUnfortunately, this scheme cannot be easily extended to more than two variables, e.g. MathObj.PowerSeries2. NoneIntegralDomain$ corresponds to a commutative ring, where a  b 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 === 0 Typical examples of IntegralDomain include integers and polynomials over a field. 5Note 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, 0where 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. 0decomposeVarPositional (repeat 10) 123 == [3,2,1] 2Returns the result of the division, if divisible. Otherwise undefined. 2Returns the result of the division, if divisible. Otherwise undefined. Allows division by zero. DIf 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. $ ! Abstract concept of a Monoid. provisional$numericprelude@henning-thielemann.deNone1We expect a monoid to adher to associativity and  the identity behaving decently. Nothing more, really.     Haskell 98stablehaskell@henning-thielemann.deNone9Instances of this class must ensure non-negative values. ?We cannot enforce this by types, but the type class constraint  NonNegative.C Cavoids accidental usage of types which allow for negative numbers. :The 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) .that lead to a memory leak for peano numbers. $ We have choosen the simple check x<=y  instead of a full-blown compare,  since we want Zero < = undefined for peano numbers.  Because of undefined values  is in general  not commutative in the sense   let (m0,(b0,d0)) = split x y  (m1,(b1,d1)) = split y x  in m0==m1 && d0==d1 #The result values are in the order 2 in which they are generated for Peano numbers. 6 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 6 Chunky.splitSpaceLeak3 and Chunky.splitSpaceLeak4. ,Default implementation for wrapped types of  and ! class.  x -| y == max 0 (x-y)-The default implementation is not efficient, Cbecause it compares the values and then subtracts, again, if safe.  max 0 (x-y) is more elegant and efficient &but not possible in the general case, since x-y& may already yield a negative number. None2This class lets us deal with the units in a ring. % tells whether an element is a unit. (The other operations let us canonically 2write an element as a unit times another element. FTwo elements a, b of a ring R are _associates_ if a=b*u for a unit u. MFor an element a, we want to write it as a=b*u where b is an associate of a. The map (a->b) is called StandardAssociate by Gap,  unitCanonical by Axiom, and canAssoc by DoCon. The map (a->u) is called canInv by DoCon and unitNormal(x).unit by Axiom.  The laws are  $ stdAssociate x * stdUnit x === x $ stdUnit x * stdUnitInv x === 1 5 isUnit u ==> stdAssociate x === stdAssociate (x*u) !Currently some algorithms assume  8 stdAssociate(x*y) === stdAssociate x * stdAssociate y Minimal definition:   and ( or ) and optionally  1Currently some algorithms assume this property. "#$%&' "#$%&'None 8A principal ideal domain is a ring in which every ideal :(the set of multiples of some generating set of elements) is principal:  That is, Ievery element can be written as the multiple of some generating element. gcd a b. gives a generator for the ideal generated by a and b. #The algorithm above works whenever mod x y is smaller  (in a suitable sense) than both x and y; )otherwise the algorithm may run forever. Laws:   divides x (lcm x y) . x `gcd` (y `gcd` z) == (x `gcd` y) `gcd` z " gcd x y * z == gcd (x*z) (y*z)  gcd x y * lcm x y == x * y (etc: canonical) Minimal definition: 5 * nothing, if the standard Euclidean algorithm work  * if  is implemented customly,  and  make use of it (Compute the greatest common divisor and - solve a respective Diophantine equation.  # (g,(a,b)) = extendedGCD x y ==> & g==a*x+b*y && g == gcd x y 8TODO: This method is not appropriate for the PID class, P because there are rings like the one of the multivariate polynomials, K where for all x and y greatest common divisors of x and y exist, M but they cannot be represented as a linear combination of x and y. Q TODO: The definition of extendedGCD does not return the canonical associate. +The Greatest Common Divisor is defined by:  gcd x y == gcd y x H divides z x && divides z y ==> divides z (gcd x y) (specification)  divides (gcd x y) x Least common multiple 9Compute the greatest common divisor for multiple numbers 0by 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 a is minimal Awith respect to the measure function of the Euclidean algorithm. (BNot efficient because it requires duplicate computations of GCDs. EHowever GCDs of neighbouring list elements were not computed before. It is also quite arbitrary, ;because only neighbouring elements are used for balancing. 2There are certainly more sophisticated solutions. !Not 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. ')*(+,-./012$)*(+,-./012NoneNothing is the smallest element. Nothing is the largest element. .It is only a monoid for non-negative numbers.   idt <*> GCD (-2) = GCD 2 5Thus, use this Monoid only for non-negative numbers! 3456 3456Noneportable provisional$numericprelude@henning-thielemann.deNone We need a Haskell 98 type class ;which provides equality test for Vector type constructors.  A Module over a ring satisfies: $ 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 space add and subtract elements scale a vector by a scalar 5Compute the linear combination of a list of vectors.  789    789%requires multi-parameter type classes provisionalmik@math.uni-jena.deNone     :;<=>             :;<=>NoneEThis is the type class of a ring with a notion of an absolute value, satisfying the laws  ( a * b === b * a $ a /= 0 => abs (signum a) === 1 $ abs a * signum a === a Minimal 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) 2 negate (max b c) === min (negate b) (negate c) 5 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, 9because we like to have expressions of foreign languages Hto be instances (cf. embedded domain specific language approach, EDSL), as well as function types. ; for complex numbers alone may have an inappropriate type, Fbecause it does not reflect that the absolute value is a real number. You might prefer Jc. 4This type class is intended for unifying algorithms -that work for both real and complex numbers. Note the similarity to  Algebra.Units:  plays the role of  stdAssociate and  plays the role of stdUnit. Actually, since  can be defined using  and ~ #we could relax the superclasses to Additive and   if his class would only contain . ?@ABCDEFGHIJK?@ABCDEFGHIJK portable (?) provisional$numericprelude@henning-thielemann.deNone similar to %d #This is an alternative show method @that is more user-friendly but also potentially more ambigious. PNecessary when mixing NumericPrelude.Numeric Rationals with Prelude98 Rationals LMNOPQRSTUVWXYZ[\]^_  LMNOPQRSTUVWXYZ[\]^_None /Field again corresponds to a commutative ring. ,Division is partially defined and satisfies  + not (isZero b) ==> (a * b) / b === a - not (isZero a) ==> a * recip a === one when it is defined. To safely call division, ,the program must take type-specific action; 2e.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) q 6Typical examples include rationals, the real numbers, 9and 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, Be.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)  !"#$%&'`abcd !"#$%&' !"#$%&'  !"#$%&'`abcdNone(&This class allows lossless conversion 3from any representation of a rational to the fixed  type. "Lossless" means - don't do any rounding. For rounding see Algebra.RealRing. With the instances for  and  =we acknowledge that these types actually represent rationals )rather than (approximated) real numbers. !However, this contradicts to the ef class. *Laws that must be satisfied by instances: $ fromRational' . toRational === id )=Lossless conversion from any representation of a rational to  *It should hold  * realToField = fromRational' . toRational Dbut it should be much more efficient for particular pairs of types, such as converting  to . "This achieved by optimizer rules. ()*efghijklmnopq()*()*()*efghijklmnopqNone+Remember that  does not specify exactly what a , b should be, Amainly 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 +,-.rstuvwxyz{|+,-.+,-. +,-.rstuvwxyz{|None/The two classes / and ` 'exist to allow convenient conversions, &primarily between the built-in types. They should satisfy  # fromInteger . toInteger === id + toRational . toInteger === toRational Conversions 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. 2A prefix function of '(Algebra.Ring.^)' Bwith 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.html 3A prefix function of '(Algebra.Field.^-)'. It has a generalised exponent. /0123}~/0123/0123/0123}~None4Minimal implementation: 6 or '(^/)'. 456789:;<= 456789:;<= 456789:;<= 456789:;<=None>@Transcendental is the type of numbers supporting the elementary Btranscendental functions. Examples include real numbers, complex Enumbers, and computable reals represented as a lazy list of rational approximations. ANote the default declaration for a superclass. See the comments  below, under 'Instance declaractions for superclasses. DThe semantics of these operations are rather ill-defined because of branch cuts, etc. Minimal complete definition: . pi, exp, log, sin, cos, asin, acos, atan )>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd'>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd'>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.deNonee A Module over a ring satisfies: $ a *> (b + c) === a *> b + a *> c " (a * b) *> c === a *> (b *> c) $ (a + b) *> c === a *> c + b *> c fscale a vector by a scalar h5Compute the linear combination of a list of vectors. ToDo: Should it use #i ? i(This function can be used to define any z as a module over . Better move to Algebra.Additive? efghijklefghijklefghijklefghijkl Nonemmmm!NonenCDivisibleSpace is used for free one-dimensional vector spaces. It  satisfies   (a </> b) *> b = a )Examples include dollars and kilometers. nononono"%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.deNonepIt must hold: ? Module.linearComb (flatten v `asTypeOf` [a]) (basis a) == v 6 dimension a v == length (flatten v `asTypeOf` [a]) q5basis of the module with respect to the scalar type, 5 the result must be independent of argument, gj should suffice. rscale a vector by a scalar s@the size of the basis, should also work for undefined argument, 5 the result must be independent of argument, gj should suffice. pqrstupqrstupqrstu pqrstu#NonevATaken number of elements must be at most the length of the list, ,otherwise the end of the list is undefined. wCDropped number of elements must be at most the length of the list, ,otherwise the end of the list is undefined. x7Split position must be at most the length of the list, Gotherwise the end of the first list and the second list are undefined. y7The index must be smaller than the length of the list, #otherwise the result is undefined. z0Zip two lists which must be of the same length. GThis 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. vwxyz9function applied to corresponding elements of the lists vwxyzvwxyzvwxyz$None$Left associative length computation #that is appropriate for types like Integer. %Right associative length computation #that is appropriate for types like Peano number. {|}~ y{|}~ y{|}~ {|}~%NoneMinimal complete definition:   or  0There are probably more laws, but some laws are  9 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) 8 truncate x === signum x * floor (abs x) 4 ceiling (toRational x) === ceiling x :: Integer 5 truncate (toRational x) === truncate x :: Integer 2 floor (toRational x) === floor x :: Integer The new function  doesn')t return the integer part of the number. FThis also removes a type ambiguity if the integer part is not needed. =Many people will associate rounding with fractional numbers, 7and thus they are surprised about the superclass being Ring not Field. 7The 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 4like the one for finding the number of digits of an   in FixedPoint-fractions module. $They are even reasonably efficient. 0I am still uncertain whether it was a good idea to add instances for Integer and friends, since calling floor or fraction( on an integer may well indicate a bug. 6The rounding functions are just the identity function and  is constant zero. /However, I decided to associate our class with Ring rather than Field, <after I found myself using repeated subtraction and testing rather than just calling fraction, $just in order to get the constraint (Ring a, Ord a) that was more general than  (RealField a). *For the results of the rounding functions we have chosen the constraint Ring instead of  ToInteger, $since this is more flexible to use, Mbut it still signals to the user that only integral numbers can be returned. This is so, because the plain Ring class only provides zero, oneF and operations that allow to reach all natural numbers but not more. *As an aside, let me note the similarities between splitFraction x and  divMod x 1 (if that were defined). HIn particular, it might make sense to unify the rounding modes somehow. The new methods  and   differ from gk semantics. They always round to . 8This means that the fraction is always non-negative and is always smaller than 1. $This is more useful in practice and .can be generalised to more than real numbers.  Since every  denominator type  supports , every  can provide  and , e.g. fractions of polynomials.  However the Ring constraint for the  ''integral'' part of  .is too weak in order to generate polynomials. ?After all, I am uncertain whether this would be useful or not. "Can there be a separate class for , ,  and  1since 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. -This function rounds to the closest integer. For fraction x == 0.5 it rounds away from zero. FThis function is not the result of an ingenious mathematical insight, 5but is simply a kind of rounding that is the fastest &on IEEE floating point architectures. 7TODO: Should be moved to a continued fraction module. ;The generic rounding functions need a number of operations Dproportional to the number of binary digits of the integer portion. :If operations like multiplication with two and comparison 7need time proportional to the number of binary digits, 3then the overall rounding requires quadratic time. 8Needs linear time with respect to the number of digits. -This and other functions using OrderDecision like floor( where argument and result are the same may be moved to a new module. &!! &NoneCounterpart of gl% but with NumericPrelude superclass.  'None,This is a convenient class for common types Cthat both form a field and have a notion of ordering by magnitude. (NoneGThis class collects all functions for _scalar_ floating point numbers. E.g. computing 8 for complex floating numbers makes certainly no sense. NoneR{|}~!"#$%),-.012357?@ABCDEFGHIJKLMNOPf||}|}~{2!"#$3%75?@A@ABCBCPDEFDEFDEFGHIGHIGHIJKLJKLJKLMNOMNOMNO,-,-.)01f)None  mNone>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~" {|}~!"#$%),-.012357?@ABCDEFGHIJKLMNOPf*%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.deNone=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:  *Square 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 4and the argument vector has at least one component. +%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.deNoneDefault definition for  that is based on  class. Default definition for  that is based on  class 4and the argument vector has at least one component.  ,%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.deNone1The 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 4and the argument vector has at least one component.  -None%Remove all zero values from the map.  .None/%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.deNone9A matrix is a twodimensional array, indexed by integers. KTransposition of matrices is just transposition in the sense of Data.List. ! 0portable provisional$numericprelude@henning-thielemann.deNone&Cons 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, 9because when adding two partial fraction representations Gthere might concur denominators that have non-trivial common divisors. Unchecked 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 y 0computes the partial fraction representation of  y % product x, where the elements of x must be irreducible. =The function transforms the factors into their standard form with respect to unit factors. 0There are more direct methods for special cases 'like polynomials over rational numbers +where the denominators are linear factors. 6The list of denominators must contain equal elements. Sorry for this hack. 6A 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. 4Zeros might be the result, that must be remove with . #Remove trailing zeros in sub-lists /because if lists are converted to fractions by  Awe 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. 4The denominators must be at least relatively prime. Since $ requires irreducible denominators, !these are also relatively prime.  Example: mulFrac (1%6) (1%4)% fails because of the common divisor 2. AWorks always but simply puts the product into the last fraction. 8Also works if the operands share a non-trivial divisor. )However the results are quite arbitrary. BExpects an irreducible denominator as associate in standard form.  5Apply a function on a specific element if it exists, -and another function to the rest of the map. !        1%requires multi-parameter type classes provisionalmik@math.uni-jena.deNone,Right (left?) group action on the Integers. CClose to, but not the same as the module action in Algebra.Module. candidates for Utility ?             2%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.deNoneGWe shall make a little bit of a hack here, enabling us to use additive Gor multiplicative syntax for groups as we wish by simply instantiating ENum with both operations corresponding to the group operation of the permutation group we' re studying EThere are quite a few way we could represent elements of permutation Fgroups: 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. "6Does not check whether the input values are in range. #These instances may need more work 2They involve converting a permutation to a table.  !"#$%&'() !"#$%&'() !"#$%&'() !"#$%&'()3None*Horner'0s scheme for evaluating a polynomial in a ring. +Horner'2s scheme for evaluating a polynomial in a module. -It'6s also helpful to put a polynomial in canonical form. -, strips leading coefficients that are zero. .+Multiply by the variable, used internally. 887 is fast if the second argument is a short polynomial, 5o relies on that fact. ADIntegrates if it is possible to represent the integrated polynomial in the given ring. (Otherwise undefined coefficients occur. *+,-./0123456789:;<=>?@ABC*+,-./0123456789:;<=>?@ABC*+,-./0123456789:;<=>?@ABC*+,-./0123456789:;<=>?@ABC4None J"For the series of a real function f compute the series for x -> f (-x) K"For the series of a real function f compute the series for x -> (f x + f (-x)) / 2 L"For the series of a real function f compute the real series for x -> (f (i*x) + f (-i*x)) / 2 TFDivide two series where the absolute term of the divisor is non-zero. @That is, power series with leading non-zero terms are the units in the ring of power series.  Knuth: Seminumerical algorithms U9Divide two series also if the divisor has leading zeros. Z;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. [,Input series must start with non-zero term. \GThe first term needs a transcendent computation but the others do not. That':s why we accept a function which computes the first term.  (exp . x)' = (exp . x) * x'  (sin . x)' = (cos . x) * x'  (cos . x)' = - (sin . x) * x' b,Input series must start with non-zero term. c Computes (log x)' , that is x'/x g/Since the inner series must start with a zero,  the first term is omitted in y. h0Compose two power series where the outer series *can be developed for any expansion point. To be more precise: CThe outer series must be expanded with respect to the leading term of the inner series. i>This function returns the series of the function in the form: '(point of the expansion, power series) 5This is exceptionally slow and needs cubic run-time. &DEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghi&DEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghi&DEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghi&DEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghi5Nonet#Evaluate (truncated) power series. u#Evaluate (truncated) power series. wHEvaluate approximations that is evaluate all truncations of the series. xHEvaluate approximations that is evaluate all truncations of the series. yHEvaluate approximations that is evaluate all truncations of the series. z It fulfills  3 evaluate x . evaluate y == evaluate (compose x y)  jklmnopqrstuvwxyzjklmnopqrstuvwxyzjklmnopqrstuvwxyzjklmnopqrstuvwxyz6None/Since the inner series must start with a zero,  the first term is omitted in y. {|}~{|}~{|}~{|}~7None)Power series of error function (almost). More precisely  erf = 2 / sqrt pi * integrate (x -> exp (-x^2)) , with  erf 0 = 0. ++++8NoneExample for a linear equation: % Setup a differential equation for y with  ! y t = (exp (-t)) * (sin t) 9 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. !The 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/In order to handle both variables equivalently Gwe maintain a list of coefficients for terms of the same total degree. That is  % eval [[a], [b,c], [d,e,f]] (x,y) == $ a + b*x+c*y + d*x^2+e*x*y+f*y^2 _Although the sub-lists are always finite and thus are more like polynomials than power series, Odivision and square root computation are easier to implement for power series.      :None;%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.deNonedenominator conversion @very efficient because it can make use of the decimal output of  <NoneThe division may be ambiguous. 0In this case an arbitrary quotient is returned.  0:4 * 2:4 == 0/:4 2:4 * 2:4 == 0/:4 =None       >NoneThe best solution seems to let   be part of the type. 2This could happen with a phantom type for modulus and a run function like pq. KThen operations with non-matching moduli could be detected at compile time and  and . could be generated with the correct modulus. ?An alternative trial can be found in module ResidueClassMaybe.  r /: m! is the residue class containing r with respect to the modulus m 4Check if two residue classes share the same modulus                     ?None+Here we try to provide implementations for { and   by making the modulus optional. 8We have to provide non-modulus operations for the cases *where both operands have Nothing modulus. *This is problematic since operations like '(/)' #depend essentially on the modulus.  A working version with disabled { and  can be found ResidueClass. =the modulus can be Nothing to denote a generic constant like { and 7 which could not be bound to a specific modulus so far r /: m! is the residue class containing r with respect to the modulus m 4Check if two residue classes share the same modulus    @None >T is a Reader monad but does not need functional dependencies .like that from the Monad Transformer Library.  !"#$%&'()*+,-./012 !"#$%&'()*+,-./012 !"#$%&'()*+,-./012 !"#$%&'()*+,-./012Aportable provisional$numericprelude@henning-thielemann.deNone31A 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. GExample: Let the quantity of length (meter, m) be the zeroth dimension D and let the quantity of time (second, s) be the first dimension,  then the composed unit m_s corresponds to the Map  [(0,1),(1,-2)] 0In future I want to have more abstraction here, - e.g. a type class from the Edison project 6 that abstracts from the underlying implementation. & Then one can easily switch between 4 Arrays, Binary trees (like Map) and what know I. 4The neutral Unit.T 5Test for the neutral Unit.T 6,Convert a List to sparse Map representation  Example: [-1,0,-2] -> [(0,-1),(2,-2)] 7Convert Map to a List 3456789:3456789:3456789:3456789:Bportable provisional$numericprelude@henning-thielemann.deNone;A common scaling for a unit. ?(An entry for a unit and there scalings. D,If True the symbols must be preceded with a !. J Though it sounds like an attribute of Scale P it must be the same for all scales and we need it M to sort positive powered unitsets to the front ? of the list of unit components. XBRaise 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 ones a0Find the exponent that lead to minimal distance  Since the list is infinite  will fail  but the sequence is convex 7 and thus we can abort when the distance stop falling *;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_<(UnitSet,distance) the UnitSet may contain powered units `abcd*;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd*QLMNOPFGHIJK?@ABCDE;<=>RSTUVWXYZ[\]^_`abcd;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdCportable provisional$numericprelude@henning-thielemann.deNonemSome 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. ~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 factors Physical constants Prefixes used for SI units 3UnitDatabase.T of units and their common scalings 3UnitDatabase.T of units and their common scalings Pefghijklmnopqrstuvwxyz{|}~Pefghijklmnopqrstuvwxyz{|}~Pelkjihgf~}|{zyxwvutsrqponmIelkjihgfmnopqrstuvwxyz{|}~DNone9This makes a type usable in the NumericPrelude framework :that was initially implemented for Haskell98 typeclasses. E.g. if a is in class !, then T a is both in class ! and in . #You can even lift container types. If  Polynomial a is in ! for all types a that are in !, then 3T (Polynomial (MathObj.Wrapper.NumericPrelude.T a)) is in  for all types a that are in .  !"#$%&'()*+,-. !"#$%&'()*+,-.ENone#Here the coefficients are vectors, Lfor example the coefficients are real and the coefficents are real vectors. Here the argument is a vector, Dfor example the coefficients are complex numbers or square matrices and the coefficents are reals. / is the functional composition of polynomials.  It fulfills  ' eval x . eval y == eval (compose x y)  /UIt 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. 0The ! instance is intensionally built  from the  + structure of the polynomial coefficients. If we would use  Integral.C a superclass, 1then the Euclidean algorithm could not determine $the greatest common divisor of e.g. [1,1] and [2]. )123456/789:;<0=>?@ABCDEF'123456/789:;<0=>?@ABCDEFF%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.deNoneGHIJKLMGHIJKLMGNone%Determine mask by Gauss elimination. &R - alternating binomial coefficients 5L - differences of translated polynomials in columns p2 = L * R^(-1) * m R * 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) NOPQRSTUV  NOPQRSTUVH%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.deNonecf. Er "Given an approximation of a root, @the degree of the polynomial and maximum value of coefficients, Afind candidates of polynomials that have approximately this root Mand show the actual value of the polynomial at the given root approximation. EThis algorithm runs easily into a stack overflow, I do not know why. DWe may also employ a more sophisticated integer relation algorithm, like PSLQ and friends. WXYZ[WXYZ[INone"The root degree must be positive. )This way we can implement multiplication $using only multiplication from type a. exponent must be non-negative exponent can be negative exponent 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))      ]^\               ]^\J portable (?) provisional$numericprelude@henning-thielemann.deNone0We like to build the Complex Algebraic instance 8 on top of the Algebraic instance of the scalar type.  This poses no problem to 5.  However, Js) requires computing the complex argument & which is a transcendent operation. 6 In order to keep the type class dependencies clean 2 for more sophisticated algebraic number types, J we introduce a type class which actually performs the radix operation. 'Complex numbers are an algebraic type.  real part imaginary part 9Construct a complex number from real and imaginary part. 8Construct a complex number with negated imaginary part. #The conjugate of a complex number.  )Scale a complex number by a real number. !EExponential 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 z, -but oriented in the positive real direction, whereas $ z has the phase of z, but unit magnitude. &DForm a complex number from polar components of magnitude and phase. '' t# is a complex value with magnitude 1  and phase t (modulo 2*?). _/The nonnegative magnitude of a complex number. JThis implementation respects the limited range of floating point numbers. The trivial implementation ) 9would overflow for floating point exponents greater than -the half of the maximum admissible exponent. 1We automatically drop in this implementation for  and  by optimizer rules. 7You should do so for your custom floating point types. +,The phase of a complex number, in the range (-?, ?]. 1 If the magnitude is zero, then so is the phase. , The function , takes a complex number and 5returns a (magnitude, phase) pair in canonical form: 9the magnitude is nonnegative, and the phase in the range (-?, ?]; 0if the magnitude is zero, then so is the phase. `Special implementation of (/) for floating point numbers ) which prevent intermediate overflows. aThe '(*>)' method can' t replace   5 because it requires the Algebra.Module constraint <bcd !"#$%&'(_)*+,efg`-hijklmnopqrstuvwaxyz{|}~ !"#$%&'()*+,- !#"&'$%,)*+(-8bcd !"#$%&'(_)*+,efg`-hijklmnopqrstuvwaxyz{|}~K%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.deNone.)Polynomial including negative exponents >RAdd lists of numbers respecting a relative shift between the starts of the lists. !The shifts must be non-negative. 3The list of relative shifts is one element shorter than the list of summands. (Infinitely many summands are permitted, 2provided that runs of zero shifts are all finite. #We could add the lists either with  or with @, D would be straightforward, but more time consuming (quadratic time) <whereas foldr is not so obvious but needs only linear time.  (stars denote the coefficients, 9 frames denote what is contained in the interim results)  sums this way:  ' | | | ******************************* ' | | +-------------------------------- ' | | ************************ ' | +---------------------------------- ' | ************ ' +------------------------------------ I.e. / would use much time find the time differences by successive subtraction 1. @ mixes this way: ' +-------------------------------- ' | ******************************* ' | +------------------------- ' | | ************************ ' | | +------------- ' | | | ************ E+Two polynomials may be stored differently. 0This function checks whether two values of type LaurentPolynomial (actually represent the same polynomial. G?Check whether a Laurent polynomial has only the absolute term, 0that is, it represents the constant polynomial. Hp(z) -> p(-z) I p(z) -> p(1/z) J&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:;<=>?@ABCDEFGHIJ./0123456789:;<=>?@ABCDEFGHIJ./0123456789:;<=>?@ABCDEFGHIJ#./0123456789:;<=>?@ABCDEFGHIJL provisional$numericprelude@henning-thielemann.deNone-U,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!) VRequires, that no digit is  (basis-1) or  (1-basis). 1The leading digit might be negative and might be -basis or basis. WMay prepend a digit. XCompress first digit. May prepend a digit. YDoes not prepend a digit. ZCompress second digit. ESometimes this is enough to keep the digits in the admissible range. Does not prepend a digit. \Eliminate leading zero digits. This will fail for zero. ]*Trim until a minimum exponent is reached. Safe for zeros. _@Accept 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 Y. c8Make sure that a number with absolute value less than 1 !has a (small) negative exponent. LAlso works with zero because it chooses an heuristic exponent for stopping. k(Split into integer and fractional part. ncf. tu o7Only return as much digits as are contained in Double. (This will speedup further computations. t$Show a number with respect to basis 10^e. xConvert from a b basis representation to a b^e basis.  Works well with every exponent. yConvert from a b^e basis representation to a b basis.  Works well with every exponent. z!Convert between arbitrary bases. /This conversion is expensive (quadratic time). | The basis must be at least ***. NNote: Equality cannot be asserted in finite time on infinite precise numbers. CIf 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. &If all values are completely defined, then it holds  $ if b then x else y == ifLazy b x y  However if b is undefined, 5then 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.y1! are positional rational numbers with respect to basis b  Get the mantissa in such a form #that it fits an expected exponent. x and (e, alignMant b e x) represent the same number. 4Add two numbers but do not eliminate leading zeros.  Add at most basis summands. 4More 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. AIf such an exponent is too small, the summation will be aborted. ?If exponents are too big, computation will become inefficient. Like , 1but it pads with zeros if the list is too short. This way it preserves  ) length (fst (splitAtPadZero n xs)) == n  help showing series summands >For obtaining n result digits it is mathematically sufficient 0to know the first (n+1) digits of the operands. 0However this implementation needs (n+2) digits, because of calls to W in both  and . We should fix that. .Undefined if the divisor is zero - of course. 8Because it is impossible to assert that a real is zero, 0the routine will not throw an error in general. UToDo: Rigorously derive the minimal required magnitude of the leading divisor digit. +Fast division for small integral divisors, 6which 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 P. ToDo: 1Rigorously derive the minimal required magnitude "of the leading digit of the root. Mathematically the nth 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 Y. .It would suffice to fully compress only every basisth iteration (digit) >and compress only the second leading digit in each iteration. 9Can the involved operations be made lazy enough to solve y = (x+frac)^2 by frac = (y-x^2-frac^2) / (2*x) ? ENewton iteration doubles the number of correct digits in every step. >Thus we process the data in chunks of sizes of powers of two. 9This way we get fastest computation possible with Newton 4but also more dependencies on input than necessary. EThe question arises whether this implementation still fits the needs of computational reals. 4The input is requested as larger and larger chunks, 1and the input itself might be computed this way, e.g. a repeated square root. Requesting one digit too much, >requires the double amount of work for the input computation, ?which in turn multiplies time consumption by a factor of four,  and so on. +Optimal fast implementation of one routine =does not preserve fast computation of composed computations. 8The routine assumes, that the integer parts is at least b^2. List.inits is defined by inits = foldr (x ys -> [] : map (x:) ys) [[]] (This is too strict for our application.  ' Prelude> List.inits (0:1:2:undefined) / [[],[0],[0,1]*** Exception: Prelude.undefined (The following routine is more lazy than  and even lazier than vw from  utility-ht package, (but it is restricted to infinite lists. &This degree of laziness is needed for sqrtFP. & Prelude> lazyInits (0:1:2:undefined) ? [[],[0],[0,1],[0,1,2],[0,1,2,*** Exception: Prelude.undefined .Absolute value of argument should be below 1. /Residue estimates will only hold for exponents with absolute value below one. The computation is based on , ,thus the denominator should not be too big. ((Say, at most 1000 for 1000000 digits.) CIt is not optimal to split the power into pure root and pure power &(that means, with integer exponents). 1The root series can nicely handle all exponents, Ebut for exponents above 1 the series summands rises at the beginning 0and thus make the residue estimate complicated. 8For powers with integer exponents the root series turns into the binomial formula, 3which is just a complicated way to compute a power 7which 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  0cos (4*x) = 8 * cos x ^ 2 * (cos x ^ 2 - 1) + 1 4sin (4*x) = 4 * sin x * cos x * (1 - 2 * sin x ^ 2)  <Note that the faster convergence is hidden by the overhead. DThe same could be achieved with a fourth power of a complex number.   x' = x - (exp x - y) / exp x  = x + (y * exp (-x) - 1) @First, the dependencies on low-significant places are currently )much more than mathematically necessary. Check  H*Number.Positional> expSmall 1000 (-1,100 : replicate 16 0 ++ [undefined]) 5(0,[1,105,171,-82,76*** Exception: Prelude.undefined  2Every multiplication cut off two trailing digits.  Z*Number.Positional> nest 8 (mul 1000 (-1,repeat 1)) (-1,100 : replicate 16 0 ++ [undefined]) *(-9,[101,*** Exception: Prelude.undefined  &Possibly the dependencies of expSmall #could be resolved by not computing mul immediately but computing mul1 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. 6Lets 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. IMaybe there is a glorious trick to reduce the computational dependencies to the mathematical ones. This is an inverse of , also known as atan2 with flipped arguments. It'=s very slow because of the computation of sinus and cosinus. However, because it uses the  implementation as estimator, @the final application of arctan series should converge rapidly. 6It could be certainly accelerated by not using cosSin and its fiddling with pi. 9Instead 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. :This implementation gets the first decimal place for free 0by 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)) 2which 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. KLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~KLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ʀQPONMLRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~KKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~M portable (?) provisional$numericprelude@henning-thielemann.deNone7Quaternions could be defined based on Complex numbers. QHowever quaternions are often considered as real part and three imaginary parts.  real part imaginary parts 5Construct a quaternion from real and imaginary part. The conjugate of a quaternion. %Scale a quaternion by a real number. 7like Module.*> but without additional class dependency Gthe same as NormedEuc.normSqr but with a simpler type class constraint *scale a quaternion into a unit quaternion 5similarity mapping as needed for rotating 3D vectors  It holds similarity (cos(a/2) +:: scaleImag (sin(a/2)) v) (0 +:: x) == (0 +:: y) where y results from rotating x around the axis v by the angle a. Let c% be a unit quaternion, then it holds .similarity c (0+::x) == toRotationMatrix c * x (The 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, 1such that quaternion addition and multiplication 1is mapped to matrix addition and multiplication. BThe determinant of the matrix equals the squared quaternion norm (). ESince complex numbers can be turned into real (orthogonal) matrices, 9a quaternion could also be converted into a real matrix. Revert . Spherical Linear Interpolation 6Can be generalized to any transcendent Hilbert space. DIn fact, we should also include the real part in the interpolation. The '(*>)' method can' t replace  5 because it requires the Algebra.Module constraint "For 0 return vector v,  for 1 return vector w vector v, must be normalized vector w, must be normalized xNoneA special reader monad. JThe 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. FWe propose this class instead of a combination of Additive and Module #for interpolation for those types, 1where scaling and addition alone makes no sense. ESuch types are e.g. internal filter parameters in signal processing: 6For 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), 5but instances of this class are more easily defined, Jand using an AffineSpace constraint instead of Module in a type signature )is important for documentation purposes. ,AffineSpace should be superclass of Module. L(But then you may ask, why not adding another superclass for Convex spaces. 9This 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. 4Start points have components that sum up to 1, e.g.   (1, 0, 0, 0)  (0, 1, 0, 0)  (0, 0, 1, 0)  (0, 0, 0, 1)  (1/4, 1/4, 1/4, 1/4) 6Then you may move along the simplex in the directions   (1, -1, 0, 0)  (0, 1, 0, -1)  (-1, -1, 3, -1) 8which are characterized by components that sum up to 0. -For example linear combination is defined by   lerp k (a,b) = (1-k)*>a + k*>b *that 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 0to provide an affine combination of two points, -since all affine combinations of more points 1can be decomposed into such simple combinations.   lerp a x y = (1-a)*>x + a*>y E.g. a*>x + b*>y + c*>z with a+b+c=1 can be written as lerp c (lerp (b/ (1-c)) x y) z. More generally you can use   lerpnorm a b x y  = lerp (b/(a+b)) x y " = (a/(a+b))*>x + (b/(a+b))*>y  for writing   a*>x + b*>y + c*>z == * lerpnorm (a+b) c (lerpnorm a b x y) z or   a*>x + b*>y + c*>z + d*>w == A lerpnorm (a+b+c) d (lerpnorm (a+b) c (lerpnorm a b x y) z) w with  a+b+c+d=1. DThe downside is, that lerpnorm requires division, that is, a field, ,whereas the computation of the coefficients )sometimes only requires ring operations. Infix variant of .  yNone.Represent the square root of a complex number 2without actually having to compute a square root. If the Bool is False, <then the square root is represented with positive real part /or zero real part and positive imaginary part. 0If the Bool is True the square root is negated.  You must use fmap" only for number type conversion.  NNone ONone)Here a residue class is a representative  and the modulus is an argument.  You cannot show a value of type , 9you can only show it with respect to a concrete modulus. Values cannot be compared, 6because the comparison result depends on the modulus. PNone5This makes a type usable with Haskell98 type classes ?that was initially implemented for NumericPrelude typeclasses. E.g. if a is in class , then T a is both in class ! and in . #You can even lift container types. If  Polynomial a is in  for all types a that are in , then .T (Polynomial (MathObj.Wrapper.Haskell98.T a)) is in ! for all types a that are in !. Qportable provisional$numericprelude@henning-thielemann.deNone0     (     (     /     Rportable provisional$numericprelude@henning-thielemann.deNone !"#$%&'()*+,-./( !"#$%&'()*+,-./( !"#$%&'()*+,-./ !"#$%&'()*+,-./SNone;denominator conversion 0123456789:;<=>?@AB0123456789:;<=>?@AB0123456789:;<=>?@AB0123456789:;<=>?@AB Haskell 98stablehaskell@henning-thielemann.deNoneE+Convert a number to a non-negative number. 3If a negative number is given, an error is raised. G+Convert a number to a non-negative number. ,A negative number will be replaced by zero. 4Use this function with care since it may hide bugs. (Results are not checked for positivity. (Results are not checked for positivity. CDEF>name of the calling function to be used in the error message G          CDEFG EFG DCCDEFG         T Haskell 98stablehaskell@henning-thielemann.deNoneH@A chunky non-negative number is a list of non-negative numbers. ,It represents the sum of the list elements. HIt is possible to represent a finite number with infinitely many chunks &by using an infinite number of zeros. Note the following problems: 9Addition 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 z{. ORemove zero chunks. S/divModLazy accesses the divisor in a lazy way. KHowever this is only relevant if the dividend is smaller than the divisor. @For large dividends the divisor will be accessed multiple times Abut since it is already fully evaluated it could also be strict. T#This function has a strict divisor Fand maintains the chunk structure of the dividend at a smaller scale.  is implemented in terms of T. 1If it is needed we could also provide a function .that accesses the divisor first in a lazy way Nand 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. JHowever changing the way of operation within one number is also not nice. 0H IJKLMN O PQ    R    ST         ! " # $ % & ' ( ) * + , - HIJKLMNOPQRST HIJMNKLROPQST.H IJKLMN O PQ    R    ST         ! " # $ % & ' ( ) * + , -Uportable provisional$numericprelude@henning-thielemann.deNoned&If all values are completely defined, then it holds  $ if b then x else y == ifLazy b x y  However if b is undefined, 9then it is at least known that the result is larger than min x y. ecf. ATo how to find the shortest list in a list of lists efficiently, 4this means, also in the presence of infinite lists.  Fhttp://www.haskell.org/pipermail/haskell-cafe/2006-October/018753.html f+On equality the first operand is returned. i+On equality the first operand is returned. kx0 <= x1 && x1 < = x2 ...  /for possibly infinite numbers in finite lists. nIn 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 qCompute '(&&)' with minimal costs. 7UVWXYZ[\]^_`abcdefghijklmnopqrstu . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C!UVWXYZ[\]^_`abcdefghijklmnopqrstu!Y[Z\]^_`abcdefghijklmnoUVWXpqrstu2UVWXY[Z\]^_`abcdefghijklmnopqrstu . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B CV provisional$numericprelude@henning-thielemann.deNonev The value  Cons b e m represents the number  b^e * (m!!0 / 1 + m!!1 / b + m!!2 / b^2 + ...). 3The interpretation of exponent is chosen such that #floor (logBase b (Cons b e m)) == e. 7That is, it is good for multiplication and logarithms. B(Because of the necessity to normalize the multiplication result, %the alternative interpretation wouldn't be more complicated.) CHowever for base conversions, roots, conversion to fixed point and !working with the fractional part the interpretation  b^e * (m!!0 / b + m!!1 / b^2 + m!!2 / b^3 + ...) would fit better. &The digits in the mantissa range from 1-base to base-1. !The representation is not unique *and cannot be made unique in finite time. *This way we avoid infinite carry ripples. {=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).  The result is still not unique, *but may be useful for further processing. |8perfect carry resolution, works only on finite numbers #vwxyz{|}~ D E F G H I J K L M N O P Q R S Tvwxyz{|}~vwxyz{|}~vwxyz{|}~ D E F G H I J K L M N O P Q R S TW+multi-type parameter classes (vector space) provisional$numericprelude@henning-thielemann.deNoneA value of type 7 stores information on how to resolve unit violations. 6 The main application of the module are certainly $ Number.Physical type instances R but in principle it can also be applied to other occasionally scalar types.  U V W X Y Z [ \ ] ^ _ U V W X Y Z [ \ ] ^ _Xgeneric instances provisional$numericprelude@henning-thielemann.deNoneJA Physics.Quantity.Value.T combines a numeric value with a physical unit. 4Construct a physical value from a numeric value and + the full vector representation of a unit. 5Test 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 ASubtract two values if the units match, otherwise return Nothing  ` a b c d e f g h i j k l m n o ` a b c d e f g h i j k l m n oY?multi-parameter type classes (VectorSpace.hs, Normalization.hs) provisional$numericprelude@henning-thielemann.deNone4Show 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. 4 The value can be used re-scale connected values 2 and display them under the label of the unit .Choose a scale where the number becomes handy ? and return the scaled number and the corresponding scale. unused unused    Z-multi-parameter type classes (VectorSpace.hs) provisional$numericprelude@henning-thielemann.deNone+This function could also return the value, B but a list of pairs (String, Integer) is easier for testing. [portable provisional$numericprelude@henning-thielemann.deNone@ p q r s t u v w x y z { | } ~  //? p q r s t u v w x y z { | } ~  |None Since amp@ is the square of the actual amplitude it must be non-negative. eigenfunction of     convolve x y t = # integrate $ \s -> x s * y(t-s) Convergence only for  c f + c g > 0.   fourier x f = , integrate $ \t -> x t * cis (-2*pi*t*f) Convergence only for c f > 0.  amplify k scales by abs k!     }None eigenfunction of       ~None Differentiate and divide by sqrt pi in order to stay in a ring. 4This way, we do not need to fiddle with pi factors. Approximate a T a* using a linear combination of translated Bell.T a. -The smaller the unit (e.g. 0.1, 0.01, 0.001) Cthe better the approximation but the worse the numeric properties. #We cannot put all information into amp of Bell, since amp4 must be real, but is complex here by construction. 9We really need at least signed amplitudes at this place, 5since we want to represent differences of Gaussians. , ( (   ```  ` ` `              `  `h !"`#$%`&'()`*+,-./012345`6789:;<=>?@ABCDEFGHIJKLMNOPQQRSSTUUVWWX`YZ[`\]^_`iab`cdefghijkl&mno`pqrstu`vw`xyz`{|b}`~s   `o   `]_` `!`!"`"""""#####i$$$$$$$$$$%`%d%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&`&&&&&&&&l&&&&&'`(`()`)))))))))))c*`******+`+++,`,,,-.`.....//////////////i////l//000000 0 0 0 0 000k00000i0000000000001111 1!1"1#1]1$1%1&1'11(1)12222*22222+2,2-2.2/202313233343536373(3833l393:3;33<3=33>3-3?3 3@3A3r3B4C4D4E4F4G4H4B4I4J4(4844l44K44L4M4?4N4 4@4~4O44P4Q44444R44444S4T555U5V5W5X5Y5Z555C5D5E5F5G5H566[6\6]6(6866l66L6~6^6_6`6a6b67777777777777O7~7c7d7e7f7g7h7i7j7k7l7m7n7o7p7q7r7s7t7u7v7w7x7y7z7{7|7}7~7888888999U999V999W9X9Y9Z9::::::::::::::::::;;;;;;;;;(;8;;L;;;~;s;;;;;;;;;;;;;;<(<8<<<<L<======Y=>>>>>>>>>>X>Y>.>>>?????????Y@@@@@@@@@@@@@@@@@@@AAAAAAAABBBBcBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC C C C C CCCCCCCCCCCCCCCCCCC C!C"C#C$C%CC&C'C(C)C*C+C,C-C.C/C0C1C2DDDDXDYD3D4D5EEUEVE6E7ECEDEEEEZE9E@E8E9E:E;E<FFF=FWFXFYFZF>F?F@FAFBFCFDFEFF(FFOFsFFFGGGUGVGCGHGIGJGKGLHHHUHWHXHYHZHHHCHMHNHOH8HPHQHRHSHTHUHH(HVHHWHOHXHYIIIZII[I\IIhII]I^I_IsI~J`JJJaJbJcJdJeJfJgJlJJhJiJdJjJkJlJmJcJnJoJpJqKKKrKUKZKsKVKtKCKuKvK5K:KK(KwKxKyKK8KKhKzK{K|K}KBK9K~LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL(L8LLLLwLLLLLlLLLLLLLLLLLLL~LLLLLLLLLLLLLLLLLsLLLLLLLLLLLLLLLLLLLLLLLLMMaMbMdMMgMlMMM4MMMMMMMMMNNNkOOOOOWOXOYOOOO7OOOPPPPXPYP5QQQQQQQQQQQQQZQQQQQQQQQQQQ~QcQQlQQQQQQQQQQQQRRRRRRRRRRRRR R R R R RRSSSjSiSSSSqSSSSSWSXSYSSSSgZTTTTTTZTT4TT T!T"T#U$U$U%U&UU'U(U)U*U(U8U+UU,U-UU.U/U0U1U2U3U4U5U6U7U8U9U:U;U<U=UVVVVV>VV?VVWVXVYV@VVVAVBVCVWDWEWWFWGWWWkWHWIWJWWKWLXXXMXNXXJXYXOXPXQXRXSXlXTXUXVYWYXYYYZY[Y\Y]Y^Y_Y`ZWZaZbZcZdZeZfZg[h[[[J[Y[i[P[l[N[X[a[M[[[[[[[[j[[[k[l[m[n[o[[p[[q[r[[ [ [s[ [ [ [[[[[[[[\t\u\v\w\x\y]]]z]{]|}~^`|Z^^^^^^^^^^^^^^_`|___________________________||g    j      !"#i$%&'()*+,9-./0123456789:;<=>?>@>A>BCDEFGZH|I|J|K|L|M|N|O|| P Q R S     T U V W X Y Z [ \        T U V W X Y Z [ \     R S T U V W X Y Z [ \    ]TUVWXYZ[\^_`abcdefgYZ[\hijklYZ[\mnopqrstuTUVWXYZ[\vwxyzXY{|}~rstuRSsTUVWXYZ[\TUVWXYZ[\sTUVWXYZ[\       """""""#%%%%%s&&'s''(()))s)***************++++++++,,,,,,,,--------../////////s//t/u/r0s0t0r22s22r22t5s5t5u555555555r59s9t9u9999r9==s=t=u=~==r>s>t>u>>>>r?s?t?@DsDtDuDDDDDDDDDDDDDDDEEEEWEXEYEEE{E|EEsEtEuEEEEEEEEErEFsFtFFFuFFrGGWGGGGGGrGHsHtHuHHrIIIJJJJJJxJJJLJ{J|JsJtJJJuJJJJJJJJJJJJJJJJ~JJJJrKKsKtKKKuKKrKwMMMMMMMsMtMuMMMMMMrxx`xxxxx(xxxxxxxxxxxxxxxxyyyyZyyyyyyyhyyyysNNWNXNYN{N|NsNtNuNNOrOO|OsOtOuOPPPPPPPPPPPPP{PP|PQ}QQsQtQQuQQrS{S|SsStSSSuSSSSSSrJYstuTtTTTYTTTTT7TTTTTTTTTTTsTT{T|TTrTuTTTTTTTTTUUU|UUsUtUuUUUUUUUUUUUUUUUV{V|VVsVtVuVVVVVVVVVVVWWsWtWuWWWWWWWrXXXXXXsXtXuXXXXXXrXX[{[|[[[[s[t[u[[[[[[[r[[||||||||||C||||||||||||||| | |<|;|}}}}}} } } }}C}}}}}} } }}}}}:}}}}9}<};}}~ ~~~~~~~~7~~~l~~~~~~~~~ ~!~~~~~@~"~:~~~~9~<~;~~#~$~%~&~~'~(~)numeric-prelude-0.4NumericPrelude.NumericNumber.NonNegativeNumericPrelude.BaseMathObj.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.ResidueClass.CheckNumber.ResidueClass.MaybeNumber.ResidueClass.ReaderNumber.Physical.UnitNumber.Physical.UnitDatabaseNumber.SI.UnitMathObj.Wrapper.Haskell98MathObj.PolynomialMathObj.PowerSumMathObj.RefinementMask2MathObj.RootSet Number.RootNumber.ComplexMathObj.LaurentPolynomialNumber.PositionalNumber.QuaternionNumber.PartiallyTranscendentalNumber.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.AffineSpaceNumber.ComplexSquareRootNumeric.NonNegativeChunkyMathObj.Gaussian.VarianceMathObj.Gaussian.BellMathObj.Gaussian.Polynomialghc-prim GHC.TypesDoubleFloatInt integer-gmpGHC.Integer.TypeIntegernon-negative-0.1Numeric.NonNegative.WrappertoNumberfromNumberUnsafeTutility-ht-0.0.9Data.Bool.HT.Private ifThenElsedomainapplyinverseToOrdfromOrdcompare ordCompare liftComparetoOrdVoltageAnalyticalVoltage Frequency Information TemperatureAngleChargeMassTimeLengthIsScalartoScalar fromScalarSqrRecipMulScalarnoValueappPrecscalarmulrecip%*%%/% applyLeftMul applyRightMul applyRecipcommute associateLeftassociateRightrecipMulmulRecip identityLeft identityRight cancelLeft cancelRight invertRecip doubleRecip recipScalarlengthtimemasschargeangle temperature information frequencyvoltage unpackVoltage packVoltageConsrunwithelementrun2run3run4run5 commutative associative leftIdentity rightIdentityidentityleftZero rightZerozero leftInverse rightInverseleftDistributiverightDistributive homomorphism rightCascade leftCascade fromFunction toFunctionfromPermutation fromCyclescyclecomposechooseclosure closureSlow+-negatesubtractsumsum1sumNestedAssociativesumNestedCommutative elementAdd elementSub elementNeg<*>.+<*>.-<*>.-$propCommutativepropAssociative propIdentity propInverseisZero defltIsZero*one fromInteger^sqrproductproduct1 scalarProductpropLeftDistributivepropRightDistributivepropLeftIdentitypropRightIdentitypropPowerCascadepropPowerProductpropPowerDistributive differentiatemoddivModdividessameResidueClassdecomposeVarPositionaldecomposeVarPositionalInf divCheckedsafeDiv divModZeroevenodd roundDownroundUpdivUppropMultipleDivpropMultipleModpropProjectAdditionpropProjectMultiplicationpropUniqueRepresentativepropZeroRepresentativepropSameResidueClassidt<*>cumulatesplit splitDefaultadd-|isUnit stdAssociate stdUnitInvstdUnitintQuery intAssociate intStandardintStandardInversepropCompositionpropInverseUnitpropUniqueAssociatepropAssociateProduct extendedGCDgcdlcmcoprimeeuclidextendedEuclidextendedGCDMulti diophantinediophantineMindiophantineMultichineseRemainderchineseRemainderMultipropMaximalDivisorpropGCDDiophantinepropExtendedGCDMultipropDiophantinepropDiophantineMinpropDiophantineMultipropDiophantineMultiMinpropDivisibleGCDpropDivisibleLCMpropGCDIdentitypropGCDCommutativepropGCDAssociativepropGCDHomogeneous propGCD_LCMpropChineseRemainderMaxrunMaxMinrunMinLCMrunLCMGCDrunGCD<*Eqeq<+>*> functorScale linearComb propCascade mulMonomialmonomialabssignumabsOrd 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<*>.*>integerMultiplybasisflatten dimension propFlatten propDimensiontakedropsplitAt!! replicate lengthLeft lengthRight elemIndex elemIndices findIndex findIndicesfractionceilingfloortruncateround roundSimplefastSplitFractionfixSplitFraction fixFractionsplitFractionIntfloorInt ceilingIntroundIntroundSimpleIntapproxRational powersOfTwopairsOfPowersOfTwo genericFloorgenericCeilinggenericTruncate genericRoundgenericFractiongenericSplitFractiongenericPosFloorgenericPosCeilinggenericHalfPosFloorDigitsgenericPosRoundgenericPosFractiongenericPosSplitFractiondecisionPosFractiondecisionPosFractionSqrTimeradixdigitsrangedecodeencodeexponent significandisNaN isInfiniteisDenormalizedisNegativeZeroisIEEEatan2updnpropUpCommutativepropDnCommutativepropUpAssociativepropDnAssociativepropUpDnDistributivepropDnUpDistributivemaxminnormnormSqrnormSqrFoldablenormSqrFoldable1 defltNorm normFoldable normFoldable1strip toMaybeScalartoScalarDefault toScalarShow Dimension transposerowscolumnsindexfromRows fromColumnsfromListformatnumRows numColumnsdiagonalrandomrandomRfromFractionSum toFractionSum toFractiontoFactoredFractionmultiToFraction hornerRevfromFactoredFractionfromFactoredFractionAltmultiFromFraction reduceHeads carryRipplenormalizeModulo removeZerosmulFracmulFrac' mulFracStupidmulFracOverlap scaleFracscaleIntmulFastindexMapMapWithKeyindexMapToListindexMapFromList mapApplySplitCyclecycleRightActioncycleLeftAction cycleAction cycleOrbit cyclesOrbitorbittakeUntilRepetitiontakeUntilRepetitionSlowkeepEssentials isEssentialcyclestoCyclestoTable fromTable errIncompat liftCmpTable2 liftTable2hornerhornerCoeffVectorhornerArgVector normalizeshiftunShiftequalsub collinear tensorProducttensorProductAltmulShearmulShearTranspose divModRev progression integrate integrateInt alternateevaluateevaluateCoeffVectorevaluateArgVector approximateapproximateCoeffVectorapproximateArgVectorholes2holes2alternate stripLeadZerodividedivideStripZerorecipProgressionpowsinCos sinCosScalar derivedLog composeTaylorinvcoeffs fromCoeffslift0lift1lift2constlift0fromPowerSerieslift1fromPowerSerieslift2fromPowerSeries 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 divideMaybedeconsbase lift2Integermodulusrepresentative factorPrec/: isCompatiblemaybeCompatiblefromRepresentative matchMaybeisCompatibleMaybetoFuncconcretegetZerogetOnegetAddgetSubgetNeggetAdditiveVarsgetMul getRingVars getDividegetRecip getFieldVars monadExample runExampleisScalar 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 unimplementeddegreeshowsExpressionPrec fromRootsreverse 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 similaritytoRotationMatrixfromRotationMatrixfromRotationMatrixDenormtoComplexMatrixfromComplexMatrixslerptoValuenotImplementedlift98_1lift98_2fromNumberWithDimensiontoNumberWithDimension&*&&/& mulToScalar divToScalarcancelToScalarunrecip absSignum*&rewriteDimensionsecondminutehourdayyearhertzmetergrammtonnecoulombvoltkelvinbitbyteinchfootyardastronomicUnitparseccons fromInteger'fromFloatBasisfromIntegerBasisfromRationalBasiscommonDenominatordefltDenominator defltShowRatio fromNumberMsgfromNumberClip fromChunkstoChunks fromChunky98 toChunky98isNull isPositive minMaxDiff divModLazy divModStrictValuablecostsvalueSuccZeroinfinityerrsubNeg fromPosEnum toPosEnum argMinFullargMin argMinimum argMaxFullargMax argMaximumisAscendingFiniteListisAscendingFiniteNumbers toListMaybeglue isAscending increaseCosts&&~andWleW isAscendingWmantissacarry commonBasis defltBaseRoot defltBaseExp defltBaseTermDivAddConstmakeLine showUnitErrorlift scalarMap scalarMap2quantityfromScalarSingle lift2Maybelift2GenerrorUnitMismatchaddMaybesubMayberatPow ratPowMaybe fromRatiomulPrecshowNat showSplit showScaled chooseScale showUnitPartdefScalefindCloseScale totalDefScalegetUnitreadsNat readUnitPart parseProductparseProductTail parsePower ignoreSpace createDictPValueliftGenliternewtonpascalbarjoulewattampereohmfaradbaud zipWithPadmapLastzipWithOverlapzipWithCheckedmapLast' mapLast'' fastFractionsignedFraction GHC.ClassesOrd $fOrdToOrd $fCInteger$fC[]$fC(,) $fCVoltage $fShowVoltage$fCInformation$fCTemperature$fCAngle $fCCharge$fCMass$fCTime $fCLength$fShowInformation$fShowTemperature $fShowAngle $fShowCharge $fShowMass $fShowTime $fShowLength$fIsScalarScalar$fCRecip$fCMul $fCScalar $fShowRecip $fShowMul $fShowScalar$fApplicativeT $fFunctorT==?deflt<*>.==?$fC(->)$fC(,,) $fCOrdering$fCBool $fCDouble$fCFloat$fCInt<=?>=??maximumminimum compareOrdelementCompare<*>.<=>?<*>.<=?<*>.>=?<*>..>?GHC.Base++GHC.ErrerrorfoldrGHC.PrimseqGHC.Listconcatfilterzip System.IOprint Data.Tuplefstsnd otherwisemap$GHC.EnumenumFrom enumFromThen enumFromToenumFromThenTo==>=fail>>=>>fmapreturnGHC.Real realToFracBoundedEnumMonadFunctorGHC.ReadReadGHC.ShowShowBoolCharOrderingIO Data.EitherEitherStringFalseTrueLeftRightLTEQGT.$!readIOreadLn appendFile writeFilereadFileinteract getContentsgetLinegetCharputStrLnputStrputCharGHC.IO.ExceptionioError Text.Readreadreadseither Data.Listunwordswordsunlineslinesfoldl1lex readParenreadList readsPrecText.ParserCombinators.ReadPReadSGHC.IOFilePath userErrorIOError Control.MonadmapM_mapM sequence_sequence=<<maxBoundminBoundfromEnumtoEnumpredsucc showParen showStringshowCharshowsShowSshowListshow showsPrecunzip3unzipzipWith3zip3 concatMaplookupnotElemelemallanyorandbreakspan dropWhile takeWhilerepeatiteratescanr1scanrfoldr1scanl1scanlfoldlnullinitlasttailhead Data.MaybemaybeNothingJustMaybeuncurrycurryasTypeOfuntilflipid/=<=&&||not<>_sumNestedCommutativesum2 $fCComplex$fCRatio $fCWord64 $fCWord32 $fCWord16$fCWord8$fCWord$fCInt64$fCInt32$fCInt16$fCInt8decomposeVarPositionalInfAux$fCSum $fCProduct$fCLast$fCFirst$fCEndo$fCDual$fCAny$fCAllGHC.NumNumdiophantineMultiMinminimizeFirstOperanddiophantineAuxpropDiophantineGenpropDiophantineMultiGen$fCMax$fCMin$fCLCM$fCGCD$fEq[]$fShowT$fCT$fCT0$fCT1 ratioPrecliftOrdstore randomR01fromRational98 $fFractionalT$fNumT $fRandomT $fStorableT $fArbitraryT$fReadT$fOrdT$fCT2$fCT3$fCa(->)$fCa[]$fCa(,,)$fCa(,) $fCIntegerT$fCTT$fCIntegerInteger $fCIntInt$fCDoubleDouble $fCFloatFloat moduleError Data.FoldableFoldable$fSqra[] $fSqra(,,) $fSqra(,)$fSqrTT$fSqrIntegerInteger $fSqrIntInt$fSqrDoubleDouble$fSqrFloatFloat$fCaMap$fCaMap0 $fSqraMap$fCaMap1$fCaMap2$fCaMap3$fCMap$fCMap0formatS randomAux indexRange indexBounds allIndices$fCaT$fEqT $fShowCycle$fCaT0$fCT4$fCT5$fCT6$fMonadT$fCT7$fCT8$fCT9$fCT10$fCT11$fCT12$fCT13$fCT14$fCT15plusPrecpolynomialDifferencecorrectConstantconvolvefloatMagnitude floatDivide$fCaT4 divModCentmodCent $fPowerDouble $fPowerFloat$fCaT1$fSqraT$fCaT2$fCaT3 scaleImag checkBoundsMAC*.+multiplyAccumulaterunMacmultiplyAccumulateModulemakeMacmakeMac2makeMac3$fApplicativeMAC $fFunctorMAC$fZeroT$fZeroT0 $fZeroDouble $fZeroFloatinUpperHalfplanemulAltmulAlt2$fCTT0$fCTT1$fCTT2$fCTT3$fCTT4$fCTT5 $fRealFloatT $fRealFracT$fRealT $fFloatingT $fIntegralT $fNFDataTfromNumberWrapliftWrap isNullList isNullListZTisNullZT equalList compareListminListmaxList fromChunky98_ toChunky98_ fromNumber_ $fMonoidT $fBoundedT$fIxT$fEnumT$fPowerTfourieramplifyampcconstantexponentPolynomial integrateRootscalarProductRoot norm1Root norm2Root normInfRoot normPRootnorm1norm2normInfnormPvariancemultiply powerRingpowerAlgebraicpowerTranscendentalc0c1c2 evaluateSqRtconvolveByTranslationconvolveByFourierfourierByTranslationtranslateComplexmodulateturnapproximateByBells RootProductbell polynomial scaleComplex eigenfunctioneigenfunction0eigenfunction1eigenfunction2eigenfunction3eigenfunctionDifferentialeigenfunctionIterativeeigenfunctionIterationdiffRevapproximateByBellsAtOnceapproximateByBellsByTranslationzipWithAbscissaslaurentAbscissas$fCRootProduct$fEqRootProduct