Are there any languages that allow units? - programming-languages

When writing the following today in C#
DateTime.Now.AddYears(-60)
I wondered whether there are any languages that allow a more natural syntax with units:
DateTime.Now - 60years
Does anyone know of any? Specifically, I'm interested in the presence of unit operators(?) that turn "60years" into e.g. "TimeSpan.FromYears(60)". It'd also be neat to be able to define your own unit operators, similar to how you can write conversion operators in C#
(Yes, I know TimeSpan doesn't cater for years -- it's an example.)

F# has units of measure. Some examples from
http://blogs.msdn.com/andrewkennedy/archive/2008/08/20/units-of-measure-in-f-part-one-introducing-units.aspx

You might be interested in F# Units of Measure support

Well the ActiveSupport library for ruby extends the Integer class with methods like hours and days which allows you to write things like:
Time.now + 5.days
But that's not really a syntax feature - it's just a method call and is possible in any language that allows you to add methods to an existing class. You could do it in C# with extension methods - though it would have to be 5.days() there.

There is a Boost C++ library for Units that makes extensive use of template metaprogramming to provide something similar to the syntax you desire.
quantity<force> F(2.0*newton);
quantity<length> dx(2.0*meter);
quantity<energy> E(work(F,dx));
http://www.boost.org/doc/libs/1_37_0/doc/html/boost_units.html

Sun's new language Fortress supports units and, if memory serves, is smart enough to stop you doing odd things such as subtracting measures of time from measures of length.
And Mathematica has units of measure and a not-too-unwieldy syntax for handling them.

Unum does pretty much exactly that for Python, allowing code like:
>>> TON + 500*KG
1.5 [t]
>>> 5E-8*M - 28*ANGSTROM
472.0 [angstrom]
>>> 3*H + 20*MIN + 15*S
3.3375 [h]
>>> H == 60*MIN
True
>>> 10000*S > 3*H + 15*MIN
False
>>>

Ada and its cousin, VHDL, directly support the concept of units. Since these languages are extremely strongly typed, units are a natural ability of the strictness of types.

See the answer on C# Extensions where the int class is extended to support methods such as Hours(), Days(), etc.
Powershell has the kB, MB, and GB operators for handling file sizes etc.
The DATE_ADD() function in MSSQL accepts units such as day, hour etc for date arithmetic.

Java's JODA library works that way.
And there's JSR-275 that proposes a units framework.
I first heard about this issue back in 1997 from Martin Fowler. He wrote about it in his "Analysis Patterns".

Not units, per se... but one way to use extension methods to give you unit-like functionality. This example is for TimeSpan, specifically.
static class TimeExtensions
{
public static TimeSpan ToDays(this int i)
{
return new TimeSpan(i, 0, 0, 0, 0);
}
public static TimeSpan ToHours(this int i)
{
return new TimeSpan(0, i, 0, 0, 0);
}
public static TimeSpan ToMinutes(this int i)
{
return new TimeSpan(0, 0, i, 0, 0);
}
public static TimeSpan ToSeconds(this int i)
{
return new TimeSpan(0, 0, 0, i, 0);
}
public static TimeSpan ToMilliseconds(this int i)
{
return new TimeSpan(0, 0, 0, 0, i);
}
}
Then, simply 4.ToMinutes() gives you a TimeSpan of 4 minutes. If you have similar base classes to work with to represent other unit types, the same sort of extension functionality can be added.
(Note: this is merely a C# representation of the Ruby example.)

When you use units, you're actually assigning a type. The conversions could be implemented through casting, or through differentiating function calls based on parameter types (function overloading). Just about any statically typed language (that allows you to define types thoroughly) would allow you to do something similar. It would make your program more robust, though those who prefer dynamically typed languages may argue that gains are small relative to time spent implementing such a thorough type system for most applications. Building a Mars Climate Orbiter would, on the other hand, merit such a type system.
The syntax is a little different, but your example strikes me as very similar to common examples of how some would use Haskell's type system (or that of any typed functional language), though, as I mentioned, this is also doable in C-like languages as well.

I gues C++ , you can make unit class with overloaded operators and some #define macros

I don't know if one exists yet, but I would expect to start seeing such things popping up as DSLs in the next couple of years. I'm thinking sort of like a next generation MATLAB or something. I'm sure there are loads of mathematical, scientific, and engineering uses for such things.

MySQL has this feature
mysql> SELECT '2008-12-31 23:59:59' + INTERVAL 1 SECOND;
-> '2009-01-01 00:00:00'
mysql> SELECT INTERVAL 1 DAY + '2008-12-31';
-> '2009-01-01'
mysql> SELECT '2005-01-01' - INTERVAL 1 SECOND;
-> '2004-12-31 23:59:59'

SQL, or atleast MySQL has some basic time based unit support.
mysql> SELECT DATE_SUB(NOW(), INTERVAL 1 DAY) AS `yesterday`, NOW() + INTERVAL 1 DAY AS `tomorrow`;
+---------------------+---------------------+
| yesterday | tomorrow |
+---------------------+---------------------+
| 2009-08-20 06:55:05 | 2009-08-22 06:55:05 |
+---------------------+---------------------+
1 row in set (0.00 sec)

I know what you mean, and I too have been curious about this. (My high school chemistry teacher was adamant that numbers without units were fairly meaningless. Anyway...)
With any strongly typed language, you can write classes for these concepts. I've written them in C++, Java and Pascal. Google "Units" and "Java" and you can find a library that has all sorts of physical measurements encapsulated like this.
C++, with it's slicker type conversions and operator overloading can make this look more natural. You can actually make things pretty slick, getting at what I think you want. Java, although it does this, will require more explicit conversions and awkward syntax.
But no, I haven't seen it.
Look for domain specific languages created for scientists, even "educational" ones.

Frink is a language purpose-built for "physical calculations" like that. From the documentation:
Frink is a practical calculating tool
and programming language designed to
make physical calculations simple, to
help ensure that answers come out
right [..]. It tracks units of measure
(feet, meters, kilograms, watts, etc.)
through all calculations, allowing you
to mix units of measure transparently
[..]
Your example in Frink:
now[] - 60 years

I have not seen such a language that supports it inherently. However you could certainly write your own Date based objects in a variety of languages, if your so inclined.

I'm sure it's not what you're looking for, but in the area of test and measurement equipment, it would not be unusual for a 'test program' to include statements which operate on values expressed with voltage, current or time units.
Very specialised stuff, though, and barely recognisable by most as programming languages.

PHP's strtotime() function does it very nicely. It takes a string and an optional time as parameters and will parse the string to figure out a new time.
Examples:
$newTime = strtotime('last monday');
$newTime = strtotime('- 2 days', $originalTime);
$newTime = strtotime('- 60 years', $originalTime);
$newTime = strtotime('+ 1 week 1 day', $originalTime);
More here: http://us2.php.net/strtotime

Not part of the language, but I've seen that done before in C, something like:
#define NOW time(0)
#define PLUS +
#define AND +
#define MINUS -
#define SECOND * 1
#define SECONDS * 1
#define MINUTE * 60
#define MINUTES * 60
#define HOUR * 3600
#define HOURS * 3600
#define DAY * 86400
#define DAYS * 86400
time_t waitUntil = NOW PLUS 1 HOUR AND 23 MINUTES;
It seemed like an abomination to me at the time, in the same class as "#define begin {" and "#define end }" - if you don't like the way the language works, use a different language; don't try to bend it to your will in such a hideous way.
It still seems like an abomination, but I've mellowed in my old age and can at least understand why maybe someone thought it was a good idea.

PowerShell has some basic support. For instance 5GB/1MB evaluates to 5120

Syntacticly, I'm not really sure what the benifit would be of
DateTime.Now + 60 years
Over
DateTime.Now.AddYears (60)
My typical method for dealing with "units" is to define constants that convert those units into the data object's base unit if multiplied. Since someone (breifly) tagged this with Ada, the Ada version would be:
Years : constant := 60.0 * 60.0 * 24.0 * 365.0;
DateTime.Now := DateTime.Now + (60.0 * Years);
I think you can do pretty much the same think in C++, except that their time objects are liable to be large integers instead of reals.

In Perl, you can use DateTime which allows such things as:
my $dt = DateTime->now
$dt->subtract( hours => 1 );

Related

Is there a non-allocating way to get the difference between two LocalDateTime points?

I do appreciate why differences between two LocalDateTime instance are expressed as Periods and not Durations, but I could not find a reason why Period is a class and not a struct.
I am helping to port a codebase that did lots of this:
DateTime t1;
DateTime t2;
TimeSpan diff = t2-t1;
// After port, with a surprising allocation
LocalDateTime t1;
LocalDateTime t2;
Period diff = t2-t1;
It seems like a bit of a perf/GC pitfall, and I'm just curious why Period is a class and not a struct?
The main reason for Period to be a class is that it would be huge - it has 6 long fields and 4 int fields. That would be 64 bytes - an awful lot to pass as a method argument etc. While some other structs in Noda Time are "pretty big" they're not that big.
But it's worth noting that the two pieces of code do radically different things. The Noda Time equivalent of TimeSpan isn't Period; it's Duration, which is a struct. If you don't need a calendrical calculation, you might want to consider converting your two LocalDateTime values to Instant values in UTC (or avoid using LocalDateTime to start with), and then take the difference between those two instants.
Internally, there are non-allocating ways of getting "the number of days" between dates, for example... we could potentially expose something like that publicly, but I think it would be worth doing benchmarking first to prove this is really important. (The GC is pretty good at collecting very-temporary objects. Sure, it's not free - but I think code would have to be doing very little other than this for it to become a major factor.)

Can I use Alloy to solve linear programming like problems?

I want to find a solution for set of numerical equations and I wondering whether Alloy could be used for that.
I've found limited information on alloy that seem to suggest (to me, at least) that it could be done, but I've found no examples of similar problems.
It certainly isn't easy, so before investing time and some money in literature I'd like to know if this is doable or not.
Simplified example:
(1) a + b = c, (2) a > b, (3) a > 0, (4) b > 0, (5) c > 0
One solution would be
a = 2, b = 1, c = 3
Any insights on the usability of Alloy or better tools / solutions would be greatly appreciated.
Kind regards,
Paul.
Daniel Jackson discourage using Alloy for numeric problems. The reason is that Alloy uses a SAT solver and this does not scale well since it severely limits the range of available integers. By default Alloy uses 4 bits for an integer: -8..7. (This can be enlarged with the run command but will of course slow down finding an answer.) The mindset of not to use numbers also influenced the syntax, there are no nice operators for numbers. I.e. addition is 5.plus[6].
That said, your problem would look like:
pred f[a,b,c : Int] {
a.plus[b] = c
a > b
a > 0
b > 0
c > 0
}
run f for 4 int
The answer can be found in the evaluator or text view. The first answer I got was a=4, b=1, c=5.
Alloy was developed around 2010 and since then there are SMT solvers that work similar to SAT solvers but can handle numeric problems as well. Alloy could be made to use those solvers I think. Would be nice because the language is incredibly nice to work with, the lack of number is a real miss.
Update Added a constraint puzzle at https://github.com/AlloyTools/models/blob/master/puzzle/einstein/einstein-wikipedia.als
Alloy is specialized as a relational constraint solver. While it can do very simple linear programming, you might want to look at a specialized tool like MiniZinc instead.

Alpha-beta tree search without recursion

I'd like to see an implementation of an alpha-beta search (negamax to be more precise) without recursion. I know the basic idea - to use one or more stacks to keep track of the levels, but having a real code would spare me a lot of time.
Having it in Java, C# or Javascript would be perfect, but C/C++ is fine.
Here's the (simplified) recursive code:
function search(crtDepth, alpha, beta)
{
if (crtDepth == 0)
return eval(board);
var moves = generateMoves(board);
var crtMove;
var score = 200000;
var i;
while (i<moves.length)
{
crtMove = moves.moveList[i++];
doMove(board, crtMove);
score = -search(crtDepth-1, -beta, -alpha);
undoMove(board, crtMove);
if (score > alpha)
{
if (score >= beta)
return beta;
alpha = score;
}
}
return alpha;
}
search(4, -200000, 200000);
Knuth and Moore published an iterative alpha-beta routine in 1975 using an ad-hoc Algol language.
An Analysis of Alpha Beta Pruning (Page 301)
Also in Chapter 9 of "Selected Papers on Analysis of Algorithms"
It doesn't look very easy to covert into C# but it might help someone who wants to do it for the pure joy of optimization.
I'm very new to chess programming so it's beyond my abilities. Plus, my biggest performance gain was when I switched from "Copy-Make" to "Make-Unmake". I'm using XNA, so getting my GC latency down to almost 0 fixed all my performance issues, now it runs faster on my 360 than it does on my PC so this optimization seems too difficult to attempt for my needs.
Also see Recursion to Iteration
For a more recent bit of code, I wrote a non-recursive Negamax routine as an option in the EasyAI python library. The specific source code is at:
https://github.com/Zulko/easyAI/blob/master/easyAI/AI/NonRecursiveNegamax.py
It uses a simple loop with a fixed array of objects (size determined by target depth) to move up and down the tree in an ordered fashion. For the particular project I was using it on, it was six times faster than the recursive version. But I'm sure each game would respond differently.
There is no way to deny that this is some dense and complex code and conversion to C/Java/C# will be ... challenging. It is pretty much nothing but border cases. :)
If you convert it to C/Java/C#, I would love to see the results. Place an link in the comment?

Programming languages where indexing starts at 1? [duplicate]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
C programming language is known as a zero index array language. The first item in an array is accessible using 0. For example double arr[2] = {1.5,2.5} The first item in array arr is at position 0. arr[0] === 1.5 What programming languages are 1 based indexes?
I've heard of the these languages start at 1 instead of 0 for array access: Algol, Matlab, Action!, Pascal, Fortran, Cobol. Is this complete?
Specificially, a 1 based array would access the first item with 1, not zero.
A list can be found on wikipedia.
ALGOL 68
APL
AWK
CFML
COBOL
Fortran
FoxPro
Julia
Lua
Mathematica
MATLAB
PL/I
Ring
RPG
Sass
Smalltalk
Wolfram Language
XPath/XQuery
Fortran starts at 1. I know that because my Dad used to program Fortran before I was born (I am 33 now) and he really criticizes modern programming languages for starting at 0, saying it's unnatural, not how humans think, unlike maths, and so on.
However, I find things starting at 0 quite natural; my first real programming language was C and *(ptr+n) wouldn't have worked so nicely if n hadn't started at zero!
A pretty big list of languages is on Wikipedia under Comparison of Programming Languages (array) under "Array system cross-reference list" table (Default base index column)
This has a good discussion of 1- vs. 0- indexed and subscriptions in general
To quote from the blog:
EWD831 by E.W. Dijkstra, 1982.
When dealing with a sequence of length N, the elements of which we
wish to distinguish by subscript, the
next vexing question is what subscript
value to assign to its starting
element. Adhering to convention a)
yields, when starting with subscript
1, the subscript range 1 ≤ i < N+1;
starting with 0, however, gives the
nicer range 0 ≤ i < N. So let us let
our ordinals start at zero: an
element's ordinal (subscript) equals
the number of elements preceding it in
the sequence. And the moral of the
story is that we had better regard
—after all those centuries!— zero as a
most natural number.
Remark:: Many programming languages have been designed without due
attention to this detail. In FORTRAN
subscripts always start at 1; in ALGOL
60 and in PASCAL, convention c) has
been adopted; the more recent SASL has
fallen back on the FORTRAN convention:
a sequence in SASL is at the same time
a function on the positive integers.
Pity! (End of Remark.)
Fortran, Matlab, Pascal, Algol, Smalltalk, and many many others.
You can do it in Perl
$[ = 1; # set the base array index to 1
You can also make it start with 42 if you feel like that. This also affects string indexes.
Actually using this feature is highly discouraged.
Also in Ada you can define your array indices as required:
A : array(-5..5) of Integer; -- defines an array with 11 elements
B : array(-1..1, -1..1) of Float; -- defines a 3x3 matrix
Someone might argue that user-defined array index ranges will lead to maintenance problems. However, it is normal to write Ada code in a way which does not depend on the array indices. For this purpose, the language provides element attributes, which are automatically defined for all defined types:
A'first -- this has the value -5
A'last -- this has the value +5
A'range -- returns the range -5..+5 which can be used e.g. in for loops
JDBC (not a language, but an API)
String x = resultSet.getString(1); // the first column
Erlang's tuples and lists index starting at 1.
Lua - disappointingly
Found one - Lua (programming language)
Check Arrays section which says -
"Lua arrays are 1-based: the first index is 1 rather than 0 as it is for many other programming languages (though an explicit index of 0 is allowed)"
VB Classic, at least through
Option Base 1
Strings in Delphi start at 1.
(Static arrays must have lower bound specified explicitly. Dynamic arrays always start at 0.)
ColdFusion - even though it is Java under the hood
Ada and Pascal.
PL/SQL. An upshot of this is when using languages that start from 0 and interacting with Oracle you need to handle the 0-1 conversions yourself for array access by index. In practice if you use a construct like foreach over rows or access columns by name, it's not much of an issue, but you might want the leftmost column, for example, which will be column 1.
Indexes start at one in CFML.
The entire Wirthian line of languages including Pascal, Object Pascal, Modula-2, Modula-3, Oberon, Oberon-2 and Ada (plus a few others I've probably overlooked) allow arrays to be indexed from whatever point you like including, obviously, 1.
Erlang indexes tuples and arrays from 1.
I think—but am no longer positive—that Algol and PL/1 both index from 1. I'm also pretty sure that Cobol indexes from 1.
Basically most high level programming languages before C indexed from 1 (with assembly languages being a notable exception for obvious reasons – and the reason C indexes from 0) and many languages from outside of the C-dominated hegemony still do so to this day.
There is also Smalltalk
Visual FoxPro, FoxPro and Clipper all use arrays where element 1 is the first element of an array... I assume that is what you mean by 1-indexed.
I see that the knowledge of fortran here is still on the '66 version.
Fortran has variable both the lower and the upper bounds of an array.
Meaning, if you declare an array like:
real, dimension (90) :: x
then 1 will be the lower bound (by default).
If you declare it like
real, dimension(0,89) :: x
then however, it will have a lower bound of 0.
If on the other hand you declare it like
real, allocatable :: x(:,:)
then you can allocate it to whatever you like. For example
allocate(x(0:np,0:np))
means the array will have the elements
x(0, 0), x(0, 1), x(0, 2 .... np)
x(1, 0), x(1, 1), ...
.
.
.
x(np, 0) ...
There are also some more interesting combinations possible:
real, dimension(:, :, 0:) :: d
real, dimension(9, 0:99, -99:99) :: iii
which are left as homework for the interested reader :)
These are just the ones I remembered off the top of my head. Since one of fortran's main strengths are array handling capabilities, it is clear that there are lot of other in&outs not mentioned here.
Nobody mentioned XPath.
Mathematica and Maxima, besides other languages already mentioned.
informix, besides other languages already mentioned.
Basic - not just VB, but all the old 1980s era line numbered versions.
Richard
FoxPro used arrays starting at index 1.
dBASE used arrays starting at index 1.
Arrays (Beginning) in dBASE
RPG, including modern RPGLE
Although C is by design 0 indexed, it is possible to arrange for an array in C to be accessed as if it were 1 (or any other value) indexed. Not something you would expect a normal C coder to do often, but it sometimes helps.
Example:
#include <stdio.h>
int main(){
int zero_based[10];
int* one_based;
int i;
one_based=zero_based-1;
for (i=1;i<=10;i++) one_based[i]=i;
for(i=10;i>=1;i--) printf("one_based[%d] = %d\n", i, one_based[i]);
return 0;
}

What programming languages support arbitrary precision arithmetic?

What programming languages support arbitrary precision arithmetic and could you give a short example of how to print an arbitrary number of digits?
Some languages have this support built in. For example, take a look at java.math.BigDecimal in Java, or decimal.Decimal in Python.
Other languages frequently have a library available to provide this feature. For example, in C you could use GMP or other options.
The "Arbitrary-precision software" section of this article gives a good rundown of your options.
Mathematica.
N[Pi, 100]
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068
Not only does mathematica have arbitrary precision but by default it has infinite precision. It keeps things like 1/3 as rationals and even expressions involving things like Sqrt[2] it maintains symbolically until you ask for a numeric approximation, which you can have to any number of decimal places.
In Common Lisp,
(format t "~D~%" (expt 7 77))
"~D~%" in printf format would be "%d\n". Arbitrary precision arithmetic is built into Common Lisp.
Smalltalk supports arbitrary precision Integers and Fractions from the beginning.
Note that gnu Smalltalk implementation does use GMP under the hood.
I'm also developping ArbitraryPrecisionFloat for various dialects (Squeak/Pharo Visualworks and Dolphin), see http://www.squeaksource.com/ArbitraryPrecisionFl.html
Python has such ability. There is an excellent example here.
From the article:
from math import log as _flog
from decimal import getcontext, Decimal
def log(x):
if x < 0:
return Decimal("NaN")
if x == 0:
return Decimal("-inf")
getcontext().prec += 3
eps = Decimal("10")**(-getcontext().prec+2)
# A good initial estimate is needed
r = Decimal(repr(_flog(float(x))))
while 1:
r2 = r - 1 + x/exp(r)
if abs(r2-r) < eps:
break
else:
r = r2
getcontext().prec -= 3
return +r
Also, the python quick start tutorial discusses the arbitrary precision: http://docs.python.org/lib/decimal-tutorial.html
and describes getcontext:
the getcontext() function accesses the
current context and allows the
settings to be changed.
Edit: Added clarification on getcontext.
Many people recommended Python's decimal module, but I would recommend using mpmath over decimal for any serious numeric uses.
COBOL
77 VALUE PIC S9(4)V9(4).
a signed variable witch 4 decimals.
PL/1
DCL VALUE DEC FIXED (4,4);
:-) I can't remember the other old stuff...
Jokes apart, as my example show, I think you shouldn't choose a programming language depending on a single feature. Virtually all decent and recent language support fixed precision in some dedicated classes.
Scheme (a variation of lisp) has a capability called 'bignum'. there are many good scheme implementations available both full language environments and embeddable scripting options.
a few I can vouch for
MitScheme (also referred to as gnu scheme)
PLTScheme
Chezscheme
Guile (also a gnu project)
Scheme 48
Ruby whole numbers and floating point numbers (mathematically speaking: rational numbers) are by default not strictly tied to the classical CPU related limits. In Ruby the integers and floats are automatically, transparently, switched to some "bignum types", if the size exceeds the maximum of the classical sizes.
One probably wants to use some reasonably optimized and "complete", multifarious, math library that uses the "bignums". This is where the Mathematica-like software truly shines with its capabilities.
As of 2011 the Mathematica is extremely expensive and terribly restricted from hacking and reshipping point of view, specially, if one wants to ship the math software as a component of a small, low price end, web application or an open source project. If one needs to do only raw number crunching, where visualizations are not required, then there exists a very viable alternative to the Mathematica and Maple. The alternative is the REDUCE Computer Algebra System, which is Lisp based, open source and mature (for decades) and under active development (in 2011). Like Mathematica, the REDUCE uses symbolic calculation.
For the recognition of the Mathematica I say that as of 2011 it seems to me that the Mathematica is the best at interactive visualizations, but I think that from programming point of view there are more convenient alternatives even if Mathematica were an open source project. To me it seems that the Mahtematica is also a bit slow and not suitable for working with huge data sets. It seems to me that the niche of the Mathematica is theoretical math, not real-life number crunching. On the other hand the publisher of the Mathematica, the Wolfram Research, is hosting and maintaining one of the most high quality, if not THE most high quality, free to use, math reference sites on planet Earth: the http://mathworld.wolfram.com/
The online documentation system that comes bundled with the Mathematica is also truly good.
When talking about speed, then it's worth to mention that REDUCE is said to run even on a Linux router. The REDUCE itself is written in Lisp, but it comes with 2 of its very own, specific, Lisp implementations. One of the Lisps is implemented in Java and the other is implemented in C. Both of them work decently, at least from math point of view. The REDUCE has 2 modes: the traditional "math mode" and a "programmers mode" that allows full access to all of the internals by the language that the REDUCE is self written in: Lisp.
So, my opinion is that if one looks at the amount of work that it takes to write math routines, not to mention all of the symbolic calculations that are all MATURE in the REDUCE, then one can save enormous amount of time (decades, literally) by doing most of the math part in REDUCE, specially given that it has been tested and debugged by professional mathematicians over a long period of time, used for doing symbolic calculations on old-era supercomputers for real professional tasks and works wonderfully, truly fast, on modern low end computers. Neither has it crashed on me, unlike at least one commercial package that I don't want to name here.
http://www.reduce-algebra.com/
To illustrate, where the symbolic calculation is essential in practice, I bring an example of solving a system of linear equations by matrix inversion. To invert a matrix, one needs to find determinants. The rounding that takes place with the directly CPU supported floating point types, can render a matrix that theoretically has an inverse, to a matrix that does not have an inverse. This in turn introduces a situation, where most of the time the software might work just fine, but if the data is a bit "unfortunate" then the application crashes, despite the fact that algorithmically there's nothing wrong in the software, other than the rounding of floating point numbers.
The absolute precision rational numbers do have a serious limitation. The more computations is performed with them, the more memory they consume. As of 2011 I don't know any solutions to that problem other than just being careful and keeping track of the number of operations that has been performed with the numbers and then rounding the numbers to save memory, but one has to do the rounding at a very precise stage of the calculations to avoid the aforementioned problems. If possible, then the rounding should be done at the very end of the calculations as the very last operation.
In PHP you have BCMath. You not need to load any dll or compile any module.
Supports numbers of any size and precision, represented as string
<?php
$a = '1.234';
$b = '5';
echo bcadd($a, $b); // 6
echo bcadd($a, $b, 4); // 6.2340
?>
Apparently Tcl also has them, from version 8.5, courtesy of LibTomMath:
http://wiki.tcl.tk/5193
http://www.tcl.tk/cgi-bin/tct/tip/237.html
http://math.libtomcrypt.com/
There are several Javascript libraries that handle arbitrary-precision arithmetic.
For example, using my big.js library:
Big.DP = 20; // Decimal Places
var pi = Big(355).div(113)
console.log( pi.toString() ); // '3.14159292035398230088'
In R you can use the Rmpfr package:
library(Rmpfr)
exp(mpfr(1, 120))
## 1 'mpfr' number of precision 120 bits
## [1] 2.7182818284590452353602874713526624979
You can find the vignette here: Arbitrarily Accurate Computation with R:
The Rmpfr Package
Java natively can do bignum operations with BigDecimal. GMP is the defacto standard library for bignum with C/C++.
If you want to work in the .NET world you can use still use the java.math.BigDecimal class. Just add a reference to vjslib (in the framework) and then you can use the java classes.
The great thing is, they can be used fron any .NET language. For example in C#:
using java.math;
namespace MyNamespace
{
class Program
{
static void Main(string[] args)
{
BigDecimal bd = new BigDecimal("12345678901234567890.1234567890123456789");
Console.WriteLine(bd.ToString());
}
}
}
The (free) basic program x11 basic ( http://x11-basic.sourceforge.net/ ) has arbitrary precision for integers. (and some useful commands as well, e.g. nextprime( abcd...pqrs))
IBM's interpreted scripting language Rexx, provides custom precision setting with Numeric. https://www.ibm.com/docs/en/zos/2.1.0?topic=instructions-numeric.
The language runs on mainframes and pc operating systems and has very powerful parsing and variable handling as well as extension packages. Object Rexx is the most recent implementation. Links from https://en.wikipedia.org/wiki/Rexx
Haskell has excellent support for arbitrary-precision arithmetic built in, and using it is the default behavior. At the REPL, with no imports or setup required:
Prelude> 2 ^ 2 ^ 12
1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190336
(try this yourself at https://tryhaskell.org/)
If you're writing code stored in a file and you want to print a number, you have to convert it to a string first. The show function does that.
module Test where
main = do
let x = 2 ^ 2 ^ 12
let xStr = show x
putStrLn xStr
(try this yourself at code.world: https://www.code.world/haskell#Pb_gPCQuqY7r77v1IHH_vWg)
What's more, Haskell's Num abstraction lets you defer deciding what type to use as long as possible.
-- Define a function to make big numbers. The (inferred) type is generic.
Prelude> superbig n = 2 ^ 2 ^ n
-- We can call this function with different concrete types and get different results.
Prelude> superbig 5 :: Int
4294967296
Prelude> superbig 5 :: Float
4.2949673e9
-- The `Int` type is not arbitrary precision, and we might overflow.
Prelude> superbig 6 :: Int
0
-- `Double` can hold bigger numbers.
Prelude> superbig 6 :: Double
1.8446744073709552e19
Prelude> superbig 9 :: Double
1.3407807929942597e154
-- But it is also not arbitrary precision, and can still overflow.
Prelude> superbig 10 :: Double
Infinity
-- The Integer type is arbitrary-precision though, and can go as big as we have memory for and patience to wait for the result.
Prelude> superbig 12 :: Integer
1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190336
-- If we don't specify a type, Haskell will infer one with arbitrary precision.
Prelude> superbig 12
1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190336

Resources