Skip to content
jianglinxPublic
forked from rchillyard/Number

About

This project is about numbers and their mathematics

Resources

Stars

1 star

Watchers

0 watching

Forks

 
 

Latest commit

 

History

91 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Codacy Badge CircleCI

Number

This project is about numbers and their mathematics. The chief features of this library are:

  • all numbers are exact wherever it is possible;
  • inexact numbers are represented along with their error bounds;
  • lazy evaluation to help avoid temporary inexact values which become part of a result;
  • there are several domains of Number (expressed with different "factors") to support angles, logarithms.

There is no such thing as accidental loss of precision (at least, provided that code follows the recommendations). For example, if you write:

val x = 1 / 2

your x will be an Int of value 0.

However, if you write the idiomatically correct form:

val x: Number = 1 / 2

then x will be a Number with value exactly one half.

Introduction

The Number project provides mathematical utilities where error bounds are tracked (and not forgotten). All functions handle the transformation or convolution of error bounds appropriately. When the error bound is sufficiently large compared to a number, that number is considered to be zero. This implies that when comparing numbers, any significant overlap of their error bounds will result in them testing as equal (according to the compare function, but not the equals function).

Numbers are represented internally as either Int, Rational, or Double. For more detail, see Representation below.

It is of course perfectly possible to use the Rational classes directly, without using the Number (or Expression) classes.

Parsing

A number with two or fewer decimal places is considered exact--a number with more than two decimal places is considered fuzzy. You can always override this by adding "*" or "..." to the end of a number with fewer than two DPs, or by adding two 0s to the end of a number with more than two decimal places.

In general, the form of a number to be parsed is:

number ::= value? factor?
factor ::= "Pi" | "pi" | "PI" | 𝛑 | 𝜀
value ::= sign? nominalValue fuzz* exponent*
nominalValue ::= integerPart ( "." fractionalPart )? | rational
rational ::= digits "/" digits
integerPart ::= digits
fractionalPart ::= digits
fuzz ::= "..." | "*" | "(" digits ")"
exponent ::= E sign? digits

Note that the e and pi symbols are, respectively, (in unicode): \uD835\uDF00 and \uD835\uDED1 (�� and ��)
A number must have at least one of the value or factor components. If no explicit factor is specified, then the number will be a Scalar (an ordinary number). If you want to get exact trigonometric values, then it's important to specify the factor as pi (or e).

Number creation

Parsing, described above is really the most precise way of specifying numerical values. But, of course, it's a lot easier to write code that uses numerical literals. For Int and Long, these give us no problems, of course. Neither is there any issue with Rational, BigDecimal, and BigInt. BigDecimal values are represented internally by Rational. There are two ways to specify Rational numbers:

  • one is to create a String of the form r"n/d" where n and d represent the numerator and the denominator;
  • the other way is simply to write n:/d (again n and d are as above).

Either of these methods will require importing the appropriate implicit classes from Rational. It's probably the simplest just to include:

import Rational._

Doubles are where the trickiest conversions apply. Writing something like Number(3.1415927) will result in a FuzzyNumber with error bounds of 5 * 10^-7. To be consistent with the String representation, Number(1.25) will result in an ExactNumber represented internally by a Rational of 5/4. However, if you want to force a number like 3.1415927 to be exact, then you will need to write

Number("3.141592700")

Rendering

Generally speaking, the output String corresponding to a Number will be the same as the input String, although at this stage of the software, that is not guaranteed. Numbers followed by "(xx)" show standard scientific notation where xx represents the standard deviation of the error with respect to the last two digits (sometimes there is only one x which corresponds to the last digit). If a Number is followed by "[xx]," this corresponds to a "box" (i.e. truncated uniform) probability density function.

Comparison

Comparison between Numbers is based on, first, equality of value. If, after any scaling for the factors is taken into account, the two values compare equal, then the Numbers are equal. For ExactNumber, comparison ends there. However, for FuzzyNumber, it is then determined whether there is significant overlap between the fuzz of the two numbers. If the overlap is sufficient that there is deemed to be a 50% probability that the numbers are really the same, then the comparison yields 0 (equal). Additionally, each of the methods involved has a signature which includes a p value (the confidence probability).

Representation

There are two kinds of Number: ExactNumber and FuzzyNumber. A FuzzyNumber has a fuzz quantity which is an optional Fuzz[Double]. The "value" of a Number is represented by the following type:

type Value = Either[Either[Option[Double], Rational], Int]

Thus, an integer x is represented by Right(x). A Rational x is represented by a Left(Right(x)). A Double x is represented by a Left(Left(Some(x))). There is also an invalid Number case which is represented by Left(Left(Left(None))).

This Value is always of the rightmost type possible: given the various possible specializations. Thus, an Int x which is in range will be represented by Right(x). Thus, a BigInt x outside the Int range will be represented by Left(Right(Rational(x))). Similarly, a Rational with numerator x and unit denominator, where x is in the range of an Int, will be represented by Right(x). It is also possible that a Double x will be represented by a Left(Right(Rational(x))). For this to happen, the value in question must have fewer than three decimal places (similar to the parsing scheme).

Factors

There are three "factors:" Scalar (for ordinary dimensionless numbers), Pi (used to represent radians or any multiple of pi), and E (for powers of the Euler number). Trigonometrical functions are designed to work with Pi. Such values are limited (modulated) to be in the range 0..2pi. However, this happens as the result of operations, so it is still possible to define a value of 2pi. For example, if you want to check that the sine of pi/2 is equal to 1 exactly, then you should write the following:

val target = (Number.pi/2).sin
target shouldBe Number.one

Similarly, if you use the atan method on a Scalar number, the result will be a number (possibly exact) whose factor is Pi.

The e factor works quite differently. It is not a simple matter of scaling. A Number of the form Number(x, e) actually evaluates to e^x rather than e x.

Lazy Evaluation

Version 1.0.3 supports lazy evaluation via a trait called Expression. The advantage of lazy evaluation is not so much performance. That's going to be neither here nor there. But it is in avoiding precision loss in some circumstances.

For example, suppose an expression you are working on involves the square root of, say, 7. However, you don't particularly pay attention to the fact that later on in the calculation, you square everything. If you don't use lazy evaluation, your final result will have an error bound, even though the true value should be proportional to exactly 7.

It's important to realize of course that you have to use the Expression mechanism.

  it should "give precise result for sqrt(7)^2" in {
    val seven: Expression = Number(7)
    val x = seven.sqrt
    val y = x ^ 2
    y shouldBe Number(7)
    y.materialize should matchPattern { case ExactNumber(_, _) => }
  }
  it should "show ^2 and sqrt for illustrative purposes" in {
    val seven = Number(7)
    val x = seven.sqrt
    val y = x power 2
    y shouldEqual Number(7)
    y shouldBe Number(7)
  }

The second test fails with "7.000000000000001 was not equal to 7," although if we do a fuzzy compare, using a custom equality test, we can at least make y shouldEqual 7 work.

The current set of expression optimizations is somewhat limited, but it catches the most important cases.

Error Bounds

The error bounds are represented by the Fuzz[Double] class. A Number with None for the fuzz is an ExactNumber, otherwise, FuzzyNumber. The are three major attributes of fuzz: shape, style (either relative or absolute), and the value (called magnitude when absolute, and tolerance when relative). Shape describes the probability density function (PDF) of values compared to the nominal value. There are currently only two types of shape:

  • Box: a truncated uniform probability density function--magnitude/tolerance relate to half the width of the non-zero probability section.
  • Gaussian: a normal probability density function: the nominal value is at the mean, and magnitude/tolerance is the standard deviation.

It's easy to convert between these four different possibilities. Generally speaking, when doing addition (or when a Number is first defined), it's convenient for the fuzz to be absolute. When performing any other operation, it's most convenient for the fuzz to be relative. It's not possible to combine two Box-shaped fuzzes: it would be possible if we allowed for trapezoids as well as rectangles, but that's far too complicated. So, whenever we combine fuzz (using convolution), we operate on Gaussian PDFs which can easily be combined.

So, why is relative fuzz usually the best? Well consider scaling--multiplying by a constant. The relative fuzz doesn't change at all. In the following, f is a constant factor. Let's assume that y = f x.

Differentiating, we get,

Δy = f Δx

Dividing both sides by f, yields

Δy / y = Δx / x

Thus, the relative fuzz of y is equal to the relative fuzz of x.

The same will be true, more or less, when we multiply two fuzzy numbers together. This time, z = x y. Therefore,

Δz = y Δx + x Δy

Dividing both sides by z:

Δz / z = Δx / x + Δy / y

Thus, the relative fuzz of z is equal to the sum of the relative fuzzes of x and y.

But, when Δx and Δy are taken from a Gaussian probability density function, the convolution of those two PDFs, is given by slightly different expressions depending on whether the PDFs are independent or correlated. See the code (Fuzz) for details.

Things get only slightly more complex when applying monadic (single operand) functions or applying a function such as z = x ^ y. Again, these formulas can be looked up in the code.

Comparing two fuzzy numbers involves subtracting the two numbers and then determining if the probability at zero is sufficiently high to consider the difference to be zero. If the probability is greater than 50% (the default--although there are method signatures that allow for different values), then we consider that the different is zero (method isZero) or that it has a signum of 0.

Versions

The Current version is 1.0.5: reimplement the e factor.

Version 1.0.4 Made improvements to Rational, removed BigInt from Value, and effected many refactorings.

Version 1.0.3 implements lazy evaluation.

Version 1.0.2 Included fixing the bug mentioned in 1.0.1 (actually a Rational bug), as well as adding the :/ operator and many other fixes/features.

Version 1.0.1 Fixed many issues with minor inconsistencies. Most important, perhaps, was the implementation of compare, along with signum and isZero. Each of these has, significantly, a signature with a confidence value (the default value is 0.5).

Initial version is 1.0.0

Future Upgrades

About

This project is about numbers and their mathematics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages