c8      !"#$%&'()*+,-./0123456789:; < = > ? @ 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 { | } ~        !"#$%&'()*+,-./01 2 3 4 5 6 7 8 9 : ; < =!>!?!@!A!B!C!D!E!F!G!H!I!J!K!L!M!N!O!P!Q!R!S!T!U!V!W!X!Y!Z![!\!]!^!_!`!a!b!c"d"e#f#g#h#i#j#k#l#m#n#o#p#q$r$s$t$u$v%w%x&y&z'{'|'}'~''''''''''''((((((((((((((())***********+++++++++++++++++++++++,,,,,,-----.////////00000000000000000000000000000000000000000011111111111111 1 1 1 1 1111111111111111111 1!1"1#1$1%1&1'1(1)1*1+1,1-1.1/101112131415161718191:1;1<1=1>1?1@1A1B1C1D1E1F1G1H1I1J1K2L2M2N2O2P2Q2R2S2T2U2V2W2X2Y2Z2[2\2]2^2_2`2a2b2c2d2e2f2g2h3i3j3k3l3m3n3o3p3q3r3s3t3u3v3w3x3y3z3{3|3}3~3333333333333333333333333444444444444444444444444444445555555555555666666666666666666666666666666777777777777777777777777777777777777777777 7 8 8 8 8889999999999999999 9!9"9#9$9%9&9'9(9)9*9+9,9-9.:/:0:1:2:3:4:5:6:7:8:9:::;:<:=:>:?:@;A;B;C;D;E;F;G;H;I;J;K;L;M;N;O;P;Q;R;S;T;U;V<W<X<Y<Z<[<\<]<^<_<`<a<b<c<d<e<f<g<h<i<j<k<l<m<n<o<p=q=r=s=t=u=v=w=x=y=z={=|=}=~==========================>>>>>>>>>>>>>>>>>>>??????????????????????????????@@@@@@@@@@@@@@@@@@@@AAABBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCC C C C C CCCCCCCCCCCCCCCCCCC C!C"C#C$C%C&C'C(C)C*C+C,C-C.C/C0C1C2C3C4C5C6C7C8C9C:C;C<C=C>C?C@CACBCCCDCECFCGCHCICJCKCLCMCNCOCPCQCRCSCTCUCVCWCXCYCZC[C\C]C^C_C`CaCbCcCdCeCfCgChCiCjCkClCmCnCoCpCqCrCsCtCuCvCwDxDyDzD{D|D}D~DDDDDDDDDDDDEEEEEEEEEEEEEEEEEEEFFFFFFFGGGGGGGGGGGGGGGHHHHHHHHHIIIIIIIIIIIIJJJJJJJJJJJJJJJJJJJKKKKKKKKKKKKKLLLLLLLLLLLLLLLLMMMMMMMMMMNNNNNNN N O O O OOOOOOOOOOOOOOOOOOO O!O"O#O$O%O&O'O(O)O*O+O,O-O.O/O0O1O2O3O4O5O6O7OQ /repeat action until result fulfills condition     'Show a value using an infix operator. .Parse a string containing an infix operator. #Compose two parsers sequentially.    ?Abstract concept of a Monoid. Will be used in order to generate provisionalmik@math.uni-jena.de>We expect a monoid to adher to associativity and the identity *behaving decently. Nothing more, really. Returns 8# if the precondition is fulfilled. &A purely functional implementation of if. Very useful in connection with 9.  condition then else +From a list of expressions choose the one, whose condition is true.  select "zero"  [(x>0, "positive"),  (x<0, "negative")] "Logical operator for implication. #Funnily because of the ordering of : it holds  implies == (<=). $keep every k-th value from the list 8Since these implementations check for the end of lists, > they may fail in fixpoint computations on infinite lists. $Make a list as long as another one  !6Compare the length of two lists over different types. GFor finite lists it is equivalent to (compare (length xs) (length ys)) but more efficient. "Gzip two lists using an arbitrary function, the shorter list is padded padding value 9function applied to corresponding elements of the lists #$0Zip two lists which must be of the same length. K 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. 9function applied to corresponding elements of the lists %& Transform   [[00,01,02,...], [[00],  [10,11,12,...], --> [10,01],  [20,21,22,...], [20,11,02],  ...] ...] With concat . shear+ you can perform a Cantor diagonalization, 8that is an enumeration of all elements of the sub-lists Awhere each element is reachable within a finite number of steps. ?It is also useful for polynomial multiplication (convolution). ' Transform   [[00,01,02,...], [[00],  [10,11,12,...], --> [01,10],  [20,21,22,...], [02,11,20],  ...] ...] It's like &8 but the order of elements in the sub list is reversed. ;Its implementation seems to be more efficient than that of &. ,If the order does not matter, better choose '. (JOperate on each combination of elements of the first and the second list. $In contrast to the list instance of  Monad.liftM2 )in holds the results in a list of lists.  It holds 1concat (outerProduct f xs ys) == liftM2 f xs ys )* It holds "splitLast xs == (init xs, last xs), but * is more efficient 8if the last element is accessed after the initial ones, "because it avoids memoizing list. +,4Remove the longest suffix of elements satisfying p. In contrast to 'reverse . dropWhile p . reverse' $this works for infinite lists, too. -0Apply a function to the last element of a list. 'If the list is empty, nothing changes. ./01reduceRepeated is an auxiliary function that, for an associative operation op, computes the same value as =reduceRepeated op a0 a n = foldr op a0 (genericReplicate n a) but applies op' O(log n) times and works for large n. 23For an associative operation op this computes  $iterateAssoc op a = iterate (op a) a but it is even faster than  map (reduceRepeated op a a) [0..] #since it shares temporary results.  The idea is: From the list &map (reduceRepeated op a a) [0,(2*n)..] we compute the list "map (reduceRepeated op a a) [0,n..], and iterate that until n==1.  !"#$%&'()*+,-./0123 !"#$%&'()*+,-./1032 !"#$%&'()*+,-./0123portable provisional$numericprelude@henning-thielemann.de45Wrap an indexable object such that it can be used in Data.Map and Data.Set. ;561Definition of an alternative ordering of objects (independent from a notion of magnitude. For an application see MathObj.PartialFraction. 78If the type has already an < instance +it is certainly the most easiest to define 7 to be equal to Ord's 7. 9Lift 7' implementation from a wrapped object. :456789:678945:545567789: portable provisional$numericprelude@henning-thielemann.de9;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrs9;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrs9TURSPQNOMVWXYZ[\]^_`abcdefghiKLIJGHEFCDAB?@jklmnop><=;qrs9;<==>?@@ABBCDDEFFGHHIJJKLLMNOOPQQRSSTUVWXYZ[\]^_`abcdefghijklmnopqrsP=>?@ABCDEFGHIJKLMNOPQRSTUVW<XY:Z[\]^_`abcdefghijklmnopqrstuvwxyz{|}~98 7Routines and abstractions for permutations of Integers. provisional$numericprelude@henning-thielemann.detEThere 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. uvwtuvwtuvwtuvwuvw 2Permutation represented by an array of the images. provisional$numericprelude@henning-thielemann.de xyz{|}~candidate for Utility 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. xyz{|}~ xyz{|}~ xyz{|}~  EAdditive 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 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. )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. -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 Algebra.ToInteger.C 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 Algebra.Core.ringPower. 8Commutativity need not be satisfied by all instances of . ' 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. 6Maybe 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  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). IntegralDomain$ 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. Allows division by zero. DIf the divisor is zero, then the divident is returned as remainder.  Haskell 98stablehaskell@henning-thielemann.de9Instances 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. x -| y == max 0 (x-y)-The default implementation is not efficient, F because it compares the values and then subtracts, again, if safe.   max 0 (x-y) is more elegant and efficient ) but not possible in the general case,  since x-y& may already yield a negative number. ?This is the type class of an ordered ring, satisfying the laws  a * b === b * a ( 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 GNote that abs is in a rather different place than it is in the Haskell 98 Prelude. In particular,  abs :: Complex -> Complex Bis not defined. To me, this seems to have the wrong type anyway; (Complex.magnitude has the correct type.  2This 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   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.  portable (?) provisional$numericprelude@henning-thielemann.de similar to Algebra.RealField.splitFraction #This is an alternative show method @that is more user-friendly but also potentially more ambigious. HNecessary when mixing NumericPrelude Rationals with Prelude98 Rationals    /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)            &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.RealField. With the instances for  and  =we acknowledge that these types actually represent rationals )rather than (approximated) real numbers. !However, this contradicts to the Algebra.Transcendental *Laws that must be satisfied by instances: $ fromRational' . toRational === id  =Lossless conversion from any representation of a rational to         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  Prelude.div b$ will round towards minus infinity. %Minimal definition: nothing required The two classes  and Algebra.ToRational.C '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.RealField. With the instances for  Prelude.Float and Prelude.Double =we acknowledge that these types actually represent rationals )rather than (approximated) real numbers. !However, this contradicts to the Algebra.Transcendental.C instance. A 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 A prefix function of '(Algebra.Field.^-)'. It has a generalised exponent.  Minimal implementation:  or '(^/)'.     %requires multi-parameter type classes provisional$numericprelude@henning-thielemann.de! 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 "scale a vector by a scalar #5Compute the linear combination of a list of vectors. ToDo: Should it use  NumericPrelude.List.zipWithMatch ? $(This function can be used to define any  as a module over . Better move to Algebra.Additive? %&'!"#$%&'!"#$%&'!""#$%&'(((()CDivisibleSpace is used for free one-dimensional vector spaces. It  satisfies  (a </> b) *> b = a )Examples include dollars and kilometers. *)*)*)**%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.de+It must hold: ? Module.linearComb (flatten v `asTypeOf` [a]) (basis a) == v 6 dimension a v == length (flatten v `asTypeOf` [a]) ,5basis of the module with respect to the scalar type, 5 the result must be independent of argument, Prelude.undefined should suffice. -scale a vector by a scalar .@the size of the basis, should also work for undefined argument, 5 the result must be independent of argument, Prelude.undefined should suffice. /0+,-./0+,-./0+,-.,-./0 1Minimal complete definition:  2 or 5 0There are probably more laws, but some laws are A (fromInteger.fst.splitFraction) a + (snd.splitFraction) a === a 4 ceiling (toRational x) === ceiling x :: Integer 5 truncate (toRational x) === truncate x :: Integer 2 floor (toRational x) === floor x :: Integer If there wouldn't be Real.C a and  ToInteger.C b constraints, Bwe could also use this class for splitting ratios of polynomials. *As an aside, let me note the similarities between splitFraction x and  x divMod 1 (if that were defined). HIn particular, it might make sense to unify the rounding modes somehow. /IEEEFloat-specific calls are removed here (cf. Prelude.RealFloat) >so probably nobody will actually use this default definition.  Henning:  New function 3 doesn')t return the integer part of the number. FThis also removes a type ambiguity if the integer part is not needed. The new methods 3 and 2  differ from Prelude.properFraction semantics. They always round to 5. 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 3 and 2, e.g. fractions of polynomials.  However the  ''integral''! part would not be of type class . "Can there be a separate class for 3, 2, 5 and 4 1since they do not need reals and their ordering? 23456789:;<7TODO: Should be moved to a continued fraction module. 123456789:;< 123456789:;< 123456723456789:;<!&=@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[\]^_`ab&=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ab&=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ab&=>?@ABCDEFGHIJKLMN>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ab"cGThis class collects all functions for _scalar_ floating point numbers. E.g. computing d8 for complex floating numbers makes certainly no sense. dcdcdcddR0  "234567<>?@ABCDEFGHIJKLMNdR >?@ABCEDFHGIKJLNM236745<d 0"# efghijklmnop efghijklmnop efgnophijklm efgfghijklmnop$%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.deqrEuclidean norm of a vector. s=A vector space equipped with an Euclidean or a Hilbert norm. Minimal definition: t t*Square of the Euclidean norm of a vector. . This is sometimes easier to implement. uqrstustqruqrrsttu%%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.devwvwvwvww&%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.dex1The 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   yxyxyxyy'%requires multi-parameter type classes provisionalmik@math.uni-jena.dez{|}~,Right (left?) group action on the Integers. CClose to, but not the same as the module action in Algebra.Module. %candidates for NumericPrelude.List ? z{|}~{z|}~z{|}~(%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.deGWe 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. Q=>?@ABCDEFGHIJKLMNOPQRSTUVW<XY:Z[\]^_`abcdefghijklmnopqrstuvwxyz{|}~980  "234567<>?@ABCDEFGHIJKLMNdnopnop)*portable provisional$numericprelude@henning-thielemann.de  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.    + portable (?) provisional$numericprelude@henning-thielemann.de"0We like to build the Complex Algebraic instance 8 on top of the Algebraic instance of the scalar type.  This poses no problem to .  However, Number.Complex.root) 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. -In order to have an efficient implementation 6 for both complex floats and exact complex numbers, 6 we define the intermediate class Complex.Divisible 2 which in fact implements the complex division. < This way we avoid overlapping and undecidable instances. - In most cases it should suffice to define B an instance of Complex.Divisible with no method implementation $ for each instance of Fractional. :Minimal implementation: toPolar or (magnitude and phase),  usually the instance definition  magnitude = defltMagnitude phase = defltPhase  is enough. .This class requires transcendent number types  although  can be computed algebraically.  The function  takes a complex number and 8 returns a (magnitude, phase) pair in canonical form: < the magnitude is nonnegative, and the phase in the range (->, >]; 3 if the magnitude is zero, then so is the phase. '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. )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, 5but 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. ,The phase of a complex number, in the range (->, >]. 1 If the magnitude is zero, then so is the phase. Special implementation of (/) for floating point numbers ) which prevent intermediate overflows. ,-%requires multi-parameter type classes provisionalmik@math.uni-jena.de.%Remove all zero values from the map. /portable provisional$numericprelude@henning-thielemann.de1A 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. The neutral Unit.T Test for the neutral Unit.T ,Convert a List to sparse Map representation  Example: [-1,0,-2] -> [(0,-1),(2,-2)] Convert Map to a List 0portable provisional$numericprelude@henning-thielemann.de*A common scaling for a unit. (An entry for a unit and there scalings. ,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. BRaise 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 <(UnitSet,distance) the UnitSet may contain powered units 0Find 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 ***1portable provisional$numericprelude@henning-thielemann.deP     Some common quantity classes.  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHICommon constants Conversion factors Physical constants Prefixes used for SI units 3UnitDatabase.T of units and their common scalings JP      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJP      !"#$%&-'(),+*/012.456789:;<=>?@ABCDEFG3IHJP      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJ2&KLMNOPHorner'&s scheme for evaluating an polynomial QRSS/ is the functional composition of polynomials.  It fulfills  ' eval x . eval y == eval (compose x y)  It'6s also helpful to put a polynomial in canonical form. , strips leading coefficients that are zero. T+Multiply by the variable, used internally. UVWXYZ[\]^^7 is fast if the second argument is a short polynomial, MathObj.PowerSeries.** relies on that fact. _`abcdeDIntegrates if it is possible to represent the integrated polynomial in the given ring. (Otherwise undefined coefficients occur. fgUIt 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. KLMNOPQRSTUVWXYZ[\]^_`abcdefgKLMNOVRSWXYZTU^[a\]_`QPbcdefgKLMLMNOPQRSTUVWXYZ[\]^_`abcdefg3/hijklmnopqr#Evaluate (truncated) power series. stIEvaluate approximations that is evaluated all truncations of the series. uv"For the series of a real function f compute the series for x -> f (-x) w"For the series of a real function f compute the series for x -> (f x + f (-x)) / 2 x"For the series of a real function f compute the real series for x -> (f (i*x) + f (-i*x)) / 2 yz{|}~FDivide 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 9Divide 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. ,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' ,Input series must start with non-zero term.  Computes (log x)' , that is x'/x  It fulfills  3 evaluate x . evaluate y == evaluate (compose x y)  /Since the inner series must start with a zero,  the first term is omitted in y. 0Compose 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. >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. /hijklmnopqrstuvwxyz{|}~/hijklmnopqrstuvwxzy{|}~/hijijklmnopqrstuvwxyz{|}~4%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.de)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: ' +-------------------------------- ' | ******************************* ' | +------------------------- ' | | ************************ ' | | +------------- ' | | | ************ +Two polynomials may be stored differently. 0This function checks whether two values of type LaurentPolynomial (actually represent the same polynomial. ?Check whether a Laurent polynomial has only the absolute term, 0that 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. 5%requires multi-parameter type classes provisionalmik@math.uni-jena.de JA matrix is a twodimensional array of ring elements, indexed by integers. @Transposition of matrices is just transposition in the sense of  Data.List. >What more do we need from our matrix class? We have addition, @subtraction and multiplication, and thus composition of generic free-module-maps. We'0re going to want to solve linear equations with #or without fields underneath, so we'#re going to want an implementation @of the Gaussian algorithm as well as most probably Smith normal Cform. Determinants are cool, and these are to be calculated either :with the Gaussian algorithm or some other goodish method. We'All want generic linear equation solving, returning one solution, Cany solution really, or nothing. Basically, this is asking for the 2preimage of a given vector over the given map, so a_11 x_1 + .. + a_1n x_n = y_1  ... a_m1 x_1 + .. + a_mn a_n = y_m Dhas really x_1,...,x_n as a preimage of the vector y_1,..,y_m under ?the map (a_ij), since obviously y_1,..,y_m = (a_ij) x_1,..,x_n ?So, generic linear equation solving boils down to the function   6portable provisional$numericprelude@henning-thielemann.de&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. PrincipalIdealDomain.C" is not really necessary here and only due to invokation of . PrincipalIdealDomain.C" 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. 7+)Power series of error function (almost). More precisely  erf = 2 / sqrt pi * integrate (x -> exp (-x^2)) , with  erf 0 = 0.  + + + 8 Example 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             9/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.  !"#$%&'()*+,-/Since the inner series must start with a zero,  the first term is omitted in y.  !"#$%&'()*+,- "!#$%&'()*+,- !"#$%&'()*+,-:./0123456789:;<=>?./0123456789:;<=>?./0123456789:;<=>?./0123456789:;<=>?;%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.de@ABCDEFGHIJKLMNOPQRSTU@ABCDEFGHIJKLMNOPQRSTU@ABCDEFGHIJKLMNOPQRSTU@ABABCDEFGHIJKLMNOPQRSTU<%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.deVWXYZ[\]^_`acf. "MathObj.Polynomial.mulLinearFactor bcdefghijklmnoVWXYZ[\]^_`abcdefghijklmnoVWXYZ[\]^_`abcdefghijklmnoVWXWXYZ[\]^_`abcdefghijklmno=portable provisional$numericprelude@henning-thielemann.de(pqrstuvwxyz{|}~(pqrstuvwxyz{|}~(z{|}~yxwvutsrqp(pqrstuvwxyz{{|}~>portable provisional$numericprelude@henning-thielemann.de(3456789:;<=>?@ABCDEFG(3456789:;<=>?@ABCDEFG?%requires multi-parameter type classes provisional$numericprelude@henning-thielemann.dedenominator conversion @very efficient because it can make use of the decimal output of c @denominator conversion  Haskell 98stablehaskell@henning-thielemann.de +Convert a number to a non-negative number. 3If a negative number is given, an error is raised. >name of the calling function to be used in the error message +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.     ABportable provisional$numericprelude@henning-thielemann.decf. 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 +On equality the first operand is returned. +On equality the first operand is returned. C provisional$numericprelude@henning-thielemann.de,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). 1The 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. Compress 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 . 8Make 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. (Split into integer and fractional part. cf. Numeric.floatToDigits 7Only 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. '!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. *+,-. Get the mantissa in such a form #that it fits an expected exponent. x and (e, alignMant b e x) represent the same number. /0123454Add two numbers but do not eliminate leading zeros. 678 Add at most basis summands. 4More summands will violate the allowed digit range. 9<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 ?@ABC>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  in both ? and :. We should fix that. D.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. EFGH+Fast division for small integral divisors, 6which occur for instance in summands of power series. IJKLMN Square root. )We need a leading digit of type Integer, +because we have to collect up to 4 digits. ,This presentation can also be considered as . ToDo: 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 . .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) ? OPENewton 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. QList.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 "but restricted to infinite lists. RS.Absolute value of argument should be below 1. TUVWXY/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. Z[\].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. `abcde 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. fghThis 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 d 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. i9Arcus tangens of arguments with absolute value less than 1 / sqrt 3. jkBEfficient computation of Arcus tangens of an argument of the form 1/n. l:This implementation gets the first decimal place for free 0by calling the arcus tangens implementation for s. m!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. nopqrst Candidate for a Utility module. uv      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuv      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuv      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvD provisional$numericprelude@henning-thielemann.dew 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. xyz{|=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 ~wxyz{|}~wxyz{|}~wxyz{xyz{|}~E portable (?) provisional$numericprelude@henning-thielemann.de7Quaternions 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. For 0 return vector v,  for 1 return vector w vector v, must be normalized vector w, must be normalized FThe division may be ambiguous. 0In this case an arbitrary quotient is returned.  0:4 * 2:4 == 0/:4 2:4 * 2:4 == 0/:4 GThe best solution seems to let  be part of the type. M Then operations with non-matching moduli could be detected at compile time  and  and . could be generated with the correct modulus. A 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 H +Here we try to provide implementations for  and  " by making the modulus optional. : We have to provide non-modulus operations for the cases , where both operands have Nothing modulus. - This is problematic since operations like (/) % depend essentially on the modulus.  A working version with disabled  and  can be found ResidueClass. =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    I )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.    J>T is a Reader monad but does not need functional dependencies +like that from the Monad Template Library. K+multi-type parameter classes (vector space) provisional$numericprelude@henning-thielemann.de A 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.    Lgeneric instances provisional$numericprelude@henning-thielemann.deJA 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 M?multi-parameter type classes (VectorSpace.hs, Normalization.hs) provisional$numericprelude@henning-thielemann.de 4Show 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   N-multi-parameter type classes (VectorSpace.hs) provisional$numericprelude@henning-thielemann.de+This function could also return the value, B but a list of pairs (String, Integer) is easier for testing.     Oportable provisional$numericprelude@henning-thielemann.de.     !"#$%&'()*+,-./01234567.     !"#$%&'()*+,-./01234567.     !"(#$%&')*+,-./02345617.      !"#$%&'()*+,-./01234567RSTRSURSVWXYZ[\Z[]Z[^Z[VZ[YZ[UZ[T_`abcdefghijklmnopqrstuvwxyz{|}~c                          c c ^ c ccccccc     c !"#$%&'()*+,-.^/01234567c89:;<=c>c?@AcBCDEcFGHIJKcLMNOccPcQRSTU c V W X Y Z [ \ ] ^ _ `!c!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!{!|!}!~!!!!"c"#c###########$c$$$$%c%&c&'^'''''''L''''''''(^(((((((((((((()c)***c***L**M*O**++J+++++++^++++++++++++++,c,,,,,-^----./^///////00000000000000000000000^0000000000000000000111111111111111111111J11111111111111111111 1 1 1 1 1111111111111111111 1!1"11#1$1%1&1'1(1)1*1+1,1-1.1/2^22021222324252262728292:2;2232<2=22>2?22@22A2B2C2D3^330313E3F3G3833Z353H3I3J3D3K3L3:3;33333M33N33@3O33A3F3P3b3Q3R3f3h3g3c3S3j3i3k33T3U3V4^44W40484X414Y4Z4[4\4]44:4^4_4`44;43444a4b4c4d4D4e4f5^55g5h5i5j5k5S5l5m55n5o6^66p6q66r6s6t6u6v6w6x626y6z6{6|66}6~666666666677b7f7h7g7c7i7k7j7l7n7p7P7F7777777777777777777777777777788888899^9909991999E9F9G9999899:9;993999F999999T::::::::::::::::::;^;;;E;F;G;8;;;;;;Z;;;;:;;P;G;;<^<<0<E<F<G<8<<Z<<<<C<<<<<<<<:<<<<P<===========^===\============F===3===========>>>>>>>>>>>>>>>>>>>?????????:?;???? ?F?G? ?h?f?g? ? ? ????b???@^@@1@0@@@@9@@@@@E@F@G@@@@@.A^A A2B^B!B"B#B$B:B;B%B&BB'B(B)B*B+B,B-B.BC/C0C1C2C3C4C^C5C6C7C8C9C:C;C<C=C>C?C@CACBCCCDCECFCGCHCICJCKCLCMCNCCOCPCQCRCSCTCUCVCWCXCYCZC[C\C]C^C_C`CaCbCcCdCeCfCgChCiC:C;CjCkClC^CmCnCoCpC3CqCrCsCCCtCuCCvCwCxCFCyCzC{C|C}C~CCCCCbCCCCCJCGCCCCCgCCCCCCCCC CC CCCCCCC CCCD^DDDDD:DD>DEDFDGDDHDMDDDDDE^EEEEEE3EEEEEEEEEEEEF:F;FjFFFFG^GGGGGGGGGFGGGGGGH^HHHHHHHHGI^IIIIEIFIGIIII9IJ^JJJJJJJJJJJJJJJJJJKKKKKK^KK2KKKKKL^LLLLLLGLLLLLL3LLLMMMMMMMMMMNNNNNNNNOO^OOOGOOO3OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOORR          RSRRS !"R#R$ % &'()*+,-./0123456789:;<;= >?@?A?B?C?D?E?FGHIJKLMNOPQ9R9STUTVTWTXTYZ[\]^_`abcdefghijkelmnopqrstuvwxyz{|}~      8RRR+++3++++++++2E2F2G2222 22GAAEAFAGAEEEEnumeric-prelude-0.0.2NumericPreludeNumber.NonNegativeNumericPrelude.MonadNumericPrelude.TextAlgebra.MonoidNumericPrelude.ConditionNumericPrelude.ListAlgebra.IndexableAlgebra.DimensionTermMathObj.PermutationMathObj.Permutation.Table Algebra.LawsAlgebra.Additive Algebra.RingAlgebra.DifferentialAlgebra.ZeroTestableAlgebra.IntegralDomainAlgebra.NonNegative Algebra.Real Algebra.UnitsAlgebra.PrincipalIdealDomain Number.Ratio Algebra.FieldAlgebra.ToRationalAlgebra.RealIntegralAlgebra.ToIntegerAlgebra.AlgebraicAlgebra.ModuleAlgebra.VectorSpaceAlgebra.DivisibleSpaceAlgebra.ModuleBasisAlgebra.RealFieldAlgebra.TranscendentalAlgebra.RealTranscendentalAlgebra.LatticeAlgebra.NormedSpace.EuclideanAlgebra.NormedSpace.MaximumAlgebra.NormedSpace.SumMathObj.Permutation.CycleList#MathObj.Permutation.CycleList.CheckAlgebra.RightModuleAlgebra.VectorNumber.ComplexAlgebra.OccasionallyScalarMathObj.AlgebraMathObj.DiscreteMapNumber.Physical.UnitNumber.Physical.UnitDatabaseNumber.SI.UnitMathObj.PolynomialMathObj.PowerSeriesMathObj.LaurentPolynomialMathObj.MatrixMathObj.PartialFractionMathObj.PowerSeries.Example(MathObj.PowerSeries.DifferentialEquationMathObj.PowerSeries2MathObj.PowerSeries.MeanMathObj.PowerSumMathObj.RootSetNumber.DimensionTermNumber.DimensionTerm.SINumber.FixedPointNumber.FixedPoint.CheckNumber.PartiallyTranscendental Number.PeanoNumber.PositionalNumber.Positional.CheckNumber.QuaternionNumber.ResidueClassNumber.ResidueClass.CheckNumber.ResidueClass.MaybeNumber.ResidueClass.FuncNumber.ResidueClass.Reader#Number.OccasionallyScalarExpressionNumber.PhysicalNumber.Physical.ShowNumber.Physical.Read Number.SI PreludeBase MyPreludeghc-prim GHC.TypesDoubleFloatInt integer-gmpGHC.Integer.TypeIntegernon-negative-0.0.5Numeric.NonNegative.WrappertoNumberfromNumberUnsafeTuntilMshowsInfixPrecreadsInfixPrec.>Cidt<*>toMaybeif'selectimpliessievesieve'sieve''sieve''' sliceHoriz sliceHoriz' sliceVert sliceVert' takeMatch splitAtMatchreplicateMatch compareLength zipWithPadzipWithOverlap zipWithMatchzipNeighborsWithshearshearTranspose outerProductpartitionMaybe splitLast propSplitLast dropWhileRevmapLastpadLeftpadRightreduceRepeatedreduceRepeatedSlow iterateAssoc iterateLeakyToOrdfromOrdcompare ordCompare liftComparetoOrdVoltageAnalyticalVoltage Frequency Information TemperatureAngleChargeMassTimeLengthSqrRecipMulScalarnoValueappPrecscalarmulrecip%*%%/% applyLeftMul applyRightMul applyRecipcommute associateLeftassociateRightrecipMulmulRecip identityLeft identityRight cancelLeft cancelRight invertRecip recipScalarlengthtimemasschargeangle temperature informationvoltage unpackVoltage packVoltagedomainapplyinverse fromFunction toFunctionfromPermutation fromCyclesidentitycyclecomposeswapchooseclosure closureSlow commutative associative leftIdentity rightIdentityleftZero rightZerozero leftInverse rightInverseleftDistributiverightDistributive homomorphism rightCascade leftCascade+-negatesubtractsumsum1propCommutativepropAssociative propIdentity propInverse*one fromInteger^sqrproductproduct1 scalarProductpropLeftDistributivepropRightDistributivepropLeftIdentitypropRightIdentitypropPowerCascadepropPowerProductpropPowerDistributive differentiateisZero defltIsZerodivmoddivModdividessameResidueClassdecomposeVarPositionaldecomposeVarPositionalInfsafeDiv divModZeroevenoddpropMultipleDivpropMultipleModpropProjectAdditionpropProjectMultiplicationpropUniqueRepresentativepropZeroRepresentativepropSameResidueClass-|abssignumisUnit stdAssociate stdUnitInvstdUnitintQuery intAssociate intStandardintStandardInversepropCompositionpropInverseUnitpropUniqueAssociatepropAssociateProduct extendedGCDgcdlcmeuclidextendedEuclidextendedGCDMulti diophantinediophantineMindiophantineMultichineseRemainderchineseRemainderMultipropMaximalDivisorpropGCDDiophantinepropExtendedGCDMultipropDiophantinepropDiophantineMinpropDiophantineMultipropDiophantineMultiMinpropDivisibleGCDpropDivisibleLCMpropGCDIdentitypropGCDCommutativepropGCDAssociativepropGCDHomogeneous propGCD_LCMpropChineseRemainderRational:% numerator denominator fromValuescalesplit% showsPrecAuto toRational98/ fromRational'^- fromRational propDivisionpropReciprocal toRationalquotremquotRem toInteger fromIntegral ringPower fieldPowersqrtroot^/ genericRootpower propSqrSqrt*> linearCombintegerMultiply propCascadebasisflatten dimension propFlatten propDimension splitFractionfractionceilingfloortruncateroundpreludeSplitFractionpreludeFraction fractionTrunc fixFractionapproxRationalpiexploglogBase**sintancosasinatanacossinhtanhcoshasinhatanhacosh propExpLog propLogExp propExpNeg propLogRecippropExpProductpropExpLogPower propLogSumpropTrigonometricPythagoras propSinPeriod propCosPeriod propTanPeriodpropSinAngleSumpropCosAngleSumpropSinDoubleAnglepropCosDoubleAngle propSinSquare propCosSquareatan2updnpropUpCommutativepropDnCommutativepropUpAssociativepropDnAssociativepropUpDnDistributivepropDnUpDistributivemaxminnormnormSqr defltNormCyclecycleRightActioncycleLeftAction cycleAction cycleOrbit cyclesOrbitorbittakeUntilRepetitiontakeUntilRepetitionSlowkeepEssentials isEssentialConsrangecyclestoCyclestoTable fromTable errIncompat liftCmpTable2 liftTable2<*Eqeq<+> functorScalePower DivisibledividePolartoPolar magnitudephaserealimagfromReal+:-: conjugate fromPolarcis propPolardefltMagnitude defltPhasedefltDivdefltPowtoScalar toMaybeScalar fromScalartoScalarDefault toScalarShowzipWith mulMonomialmonomialstripisScalar fromVectortoVectorratScale ratScaleMayberatScaleMaybe2ScalesymbolUnitSetunit independent defScaleIx reciprocalscales InitScale initSymbolinitMag initIsUnit initDefault InitUnitSetinitUnitinitIndependent initScales extractOne initScale initUnitSet createScale createUnitSet showableUnitpowerOfUnitSet powerOfScaleshowExppositiveToFront decompose findIndep findClosestevalDist findBestExp findMinExpdistLE distances listMultiples Dimensiondistanceareavolume frequencyspeed accelerationforcepressureenergycurrent resistance capacitance angularSpeeddataRatepercentfourthhalf threeFourthsecondsPerMinutesecondsPerHour secondsPerDaysecondsPerYear meterPerInch meterPerFoot meterPerYardmeterPerAstronomicUnitmeterPerParseck2deg180grad200 radPerDeg radPerGradbytesizeaccelerationOfEarthGravitymach speedOfLight electronVoltcalorien horsePoweryoctozeptoattofemtopiconanomicromillicentidecidecahectokilomegagigaterapetaexazettayotta databaseRead databaseShowdatabasecoeffs fromCoeffsshowsExpressionPrechorner'hornerevalshiftunShiftconstequaladdsub tensorProducttensorProduct'mulShearmulShearTranspose progression integrate integrateInt fromRoots alternatelift0lift1lift2evaluateapprox approximateholes2holes2alternate stripLeadZerodivideStripZerorecipProgressionpowsinCos sinCosScalar derivedLogcomp composeTaylorinvexpon!fromShiftCoeffsfromPolynomialfromPowerSeriesbounds translateseriesaddShiftedMany addShifted divExample equivalent identical isAbsolutereverseadjointtwist transposerowscolumnsfromListnumRows numColumns zeroMatrixpreimagefromFractionSum toFractionSum toFractiontoFactoredFractionmultiToFraction hornerRevfromFactoredFractionfromFactoredFractionAltmultiFromFraction reduceHeads carryRipplenormalizeModulo removeZerosmulFracmulFrac' mulFracStupidmulFracOverlap scaleFracscaleIntmulFastindexMapMapWithKeyindexMapToListindexMapFromList mapApplySplit recipExplexpExplsinExplcosExpltanExpl tanExplSievelogExplatanExplsinhExplcoshExpl atanhExplpowExplsqrtExplerfexpODEsinODEcosODEtanODE tanODESievelogODE recipCircleasinODEatanODEsqrtODEacosODEsinhODEcoshODEatanhODEpowODE solveDiffEq0 verifyDiffEq0 propDiffEq0 solveDiffEq1 verifyDiffEq1 propDiffEq1CoreisValidcheckfromPowerSeries0fromPowerSeries1lift0fromPowerSerieslift1fromPowerSerieslift2fromPowerSeries swapVariablesdifferentiate0differentiate1 integrate0 integrate1diffComp logarithmic elemSym3_2 quadratic quadraticMVF quadraticDiff quadratic2quadraticDiff2 harmonicMVF harmonic2 harmonicDiff2 arithmeticMVF arithmetic2arithmeticDiff2 geometricMVF geometric2geometricDiff2meanValueDiff2sums fromElemSym divOneFlipfromElemSymDenormalized toElemSym toElemSymIntelemSymFromPolynomial binomials approxSeriespropOp toPolynomial toPowerSums fromPowerSumsaddRootliftPowerSum1GenliftPowerSum2Gen liftPowerSum1 liftPowerSum2liftPowerSumInt1liftPowerSumInt2addIntmulIntpowInt fromNumberfromNumberWithDimensiontoNumberWithDimensionmapFst&*&&/& mulToScalar divToScalarcancelToScalarunrecip absSignum*&rewriteDimensionsecondminutehourdayyearhertzmetergrammtonnecoulombvoltkelvinbitbyteinchfootyardastronomicUnitparsec fromFloatfromFixedPointshowPositionalDecshowPositionalHexshowPositionalBinshowPositionalBasisliftShowPosToInt toPositional magnitudesevalPowerSeries arctanSmallarctanpiConstexpSmalleConst recipEConst approxLogBaselnSmalllncons fromInteger'fromFloatBasisfromIntegerBasisfromRationalBasiscommonDenominatordefltDenominator defltShowlegacyInstanceRatio fromNumberMsgfromNumberCliptoValueSuccZeroinfinityerrsubNeg isAscending fromPosEnum toPosEnum argMinFullargMin argMinimum argMaxFullargMax argMaximumSeriesBasisExponentDigitMantissa FixedPoint moveToZero checkPosDigit checkDigit nonNegativenonNegativeMantcompress compressFirst compressMantcompressSecondMant prependDigittrim trimUntiltrimOnce decreaseExp pumpFirst decreaseExpFP pumpFirstFP negativeExpfromBaseCardinalfromBaseInteger mantissaToNummantissaFromCardmantissaFromIntmantissaFromFixedIntfromBaseRational toFixedPointtoDouble fromDoublefromDoubleApproxfromDoubleRoughmantLengthDoubleliftDoubleApproxliftDoubleRoughshowDecshowHexshowBin showBasis powerBasis rootBasis fromBasis fromBasisMantcmp lessApproxtrunc equalApproxalign alignMantabsoluteabsMant fromLaurent toLaurent liftLaurent2liftLaurentManynegaddSomeaddMany seriesPlainsplitAtPadZerosplitAtMatchPadZerotruncSeriesSummands scaleSimple scaleMant mulSeriesdivMant divMantSlow divIntMant divIntMantInfdivInt sqrtDriversqrtMantsqrtFP sqrtNewton sqrtFPNewton lazyInits expSeries expSeriesLazy expSmallLazyintPower cardPower powerSeries powerSmall cosSinhSmall cosSinSmall cosSinFourthcosSincotlnSerieslnNewton lnNewton' arctanSeries arctanStem arctanClassicminusOnenestflipPair sliceVertPairbaseexponentmantissacarry commonBasis defltBaseRoot defltBaseExp defltBase+:: normalize crossProduct similaritytoRotationMatrixfromRotationMatrixfromRotationMatrixDenormtoComplexMatrixfromComplexMatrixslerp divideMaybemodulusrepresentative factorPrec/: isCompatiblemaybeCompatiblefromRepresentative matchMaybeisCompatibleMaybeconcretetoFuncgetZerogetOnegetAddgetSubgetNeggetAdditiveVarsgetMul getRingVars getDividegetRecip getFieldVars monadExample runExampleTermDivAddConstmakeLine showUnitErrorlift scalarMap scalarMap2quantityfromScalarSingle lift2Maybelift2GenerrorUnitMismatchaddMaybesubMayberatPow ratPowMaybe fromRatiomulPrecshowNat showSplit showScaled chooseScale showUnitPartdefScalefindCloseScale totalDefScalegetUnitreadsNat readUnitPart parseProductparseProductTail parsePower ignoreSpace createDictPValueliftGenliternewtonpascalbarjoulewattampereohmfaradbaud Data.MaybeJustGHC.ListzipWith3GHC.BoolBool GHC.ClassesOrdGHC.Base++GHC.ErrerrorfoldrGHC.Primseqconcatfilterzip System.IOprint Data.Tuplefstsnd otherwisemapGHC.EnumenumFrom enumFromThen enumFromToenumFromThenTo==>=fail>>=>>returnBoundedEnumMonadFunctorGHC.ReadReadGHC.ShowShowChar GHC.OrderingOrderingIO Data.EitherEitherStringFalseTrueLeftRightshowShowSPrelude$!readIOreadLn appendFile writeFilereadFileinteract getContentsgetLinegetCharputStrLnputStrputCharSystem.IO.ErrorcatchGHC.IO.ExceptionioError Text.Readreadreadseither Data.Listunwordswordsunlineslinesfoldl1minimummaximumlex readParenreadList readsPrecGHC.Real realToFrac undefinedText.ParserCombinators.ReadPReadSGHC.IOFilePathIOError userError Control.MonadmapM_mapM sequence_sequence=<< showParen showStringshowCharshowsshowList showsPrecunzip3unzipzip3!! concatMaplookupnotElemelemallanyorandbreakspansplitAtdroptake dropWhile takeWhile replicaterepeatiteratescanr1scanrfoldr1scanl1scanlfoldlnullinitlasttailheadmaybeNothingMaybemaxBoundminBoundfromEnumtoEnumpredsuccasTypeOfuntil$flip.idfmapuncurrycurrynot||&&/=<=><GTEQLTdecomposeVarPositionalInfAuxminimizeFirstOperanddiophantineAuxdiophantineMultiMinpropDiophantineGenpropDiophantineMultiGen ratioPrecliftOrdplusPrec orthoRight orthoLeftfloatMagnitudedefltMagnitudeSqr divModCentmodCentfloatDivmulLinearFactorfromNumberWrapliftWrapmapPairmapSnd scaleImag checkBounds