4.66667

4.7 | 17 ratings Rate this file 189 downloads (last 30 days) File Size: 2.85 MB File ID: #22725

Variable Precision Integer Arithmetic

by John D'Errico

 

19 Jan 2009 (Updated 22 Nov 2009)

Code covered by BSD License  

Arithmetic with integers of fully arbitrary size. Arrays and vectors of vpi numbers are supported.

Download Now | Watch this File

File Information
Description

Every once in a while, I've wanted to do arithmetic with large integers with magnitude exceeding that which can fit into MATLAB's standard data types. Since I don't have the symbolic toolbox, the simple solution was to write it in MATLAB. I did that in these tools which are entirely written in MATLAB, so there is no need for compiled code.

Arithmetic is simple with the vpi tools.

A = vpi(17)^17
ans =
827240261886336764177

17 + A^17
ans =
39786732894291535047752038041559739510060813980024082
30012867731573722066105737100731556603857745946047229
53759676529121155309750944582301597489457676380805029
59227566911971103003303064782118652210655457390045806
99039190393572334521701109889855832341416056005878848
49943142324389193616484809157960034059531548585473213
36465170635561696613297503569949729314
 
There are also a few nice add ons, for example a tool to compute exact binomial coefficients for large arguments, or large factorials, or convert binary numbers with thousands of digits to decimal (vpi) form.

For example, the existing nchoosek function in matlab gets upset for even reasonably small binomial coefficients.

nchoosek(100,50)
Warning: Result may not be exact. Coefficient is greater than 1.000000e+15
 and is only accurate to 15 digits.
> In nchoosek at 66
ans =
   1.0089e+29

However, nchoosek has no such issues on vpi numbers.

nchoosek(vpi(100),50)
ans =
100891344545564193334812497256

Similarly, the computation of factorial(171) will cause an overflow. While I'll admit that there are many good ways to avoid this problem, the factvpi function has no problems at all.

factorial(171)
ans =
   Inf

factorial(vpi(171))
ans =
12410180702176678234248405241031039926166055775016931
85388951803611996075221691752992751978120487585576464
95950167038705280988985869071076733124203221848436431
04735778899685482782907545415619648521534683180442932
39598173696899657235903947616152278558180061176365108
428800000000000000000000000000000000000000000

There are now GCD and LCM tools, both of which can accept more than two input arguments.

lcm(vpi(123452356),12344332,65364467)
ans =
3557547184310976844988

I've also put in some tools that can test for primality. For example, the Mersenne prime:

p = vpi(2)^127 - 1
ans =
170141183460469231731687303715884105727

isprime(p)
ans =
     1

Factoring of vpi numbers is now implemented.

factor(vpi('1234567890123456789'))
ans =
       3 3 101 3541 3607 3803 27961

Vectors or arrays of vpi numbers work very nicely now.

A = vpi(eye(3))*3 + 1
A =
   4 1 1
   1 4 1
   1 1 4

A^17
ans =
   5642305908354 5642176768191 5642176768191
   5642176768191 5642305908354 5642176768191
   5642176768191 5642176768191 5642305908354

Dozens of other tools are also included. I've even included a tool just for fun that will convert a number into a readable text version of it as a large integer.

vpi2english(vpi('12000000110022987'))
ans =
twelve quadrillion, one hundred ten million, twenty two thousand, nine hundred eighty seven

For those Project Euler solvers around, vpi makes many of the problems easy to solve.

Addendum - Ben Petschel has graciously given me code for unique and sortrows operations on vpi arrays. Many thanks to Ben!

Acknowledgements

The author wishes to acknowledge the following in the creation of this submission:
Multiple Precision Toolbox for MATLAB
This submission has inspired the following:
Multiple-root polynomial solved by partial fraction expansion, Fibonacci and Lucas numbers, nextprime, sumsqint, Fractions Toolbox, num2vpi - Converts input exactly into vpi, binomfactors

MATLAB release MATLAB 7.5 (R2007b)
Zip File Content  
Published M Files demo_vpi
Other Files
license.txt,
VariablePrecisionIntegers/@vpi/_primeslist_.mat,
VariablePrecisionIntegers/@vpi/abs.m,
VariablePrecisionIntegers/@vpi/ceil.m,
VariablePrecisionIntegers/@vpi/comparemagnitudes.m,
VariablePrecisionIntegers/@vpi/conv.m,
VariablePrecisionIntegers/@vpi/cumprod.m,
VariablePrecisionIntegers/@vpi/cumsum.m,
VariablePrecisionIntegers/@vpi/digits.m,
VariablePrecisionIntegers/@vpi/disp.m,
VariablePrecisionIntegers/@vpi/display.m,
VariablePrecisionIntegers/@vpi/double.m,
VariablePrecisionIntegers/@vpi/Edigits.mat,
VariablePrecisionIntegers/@vpi/eq.m,
VariablePrecisionIntegers/@vpi/exp.m,
VariablePrecisionIntegers/@vpi/factor.m,
VariablePrecisionIntegers/@vpi/factorial.m,
VariablePrecisionIntegers/@vpi/find.m,
VariablePrecisionIntegers/@vpi/fix.m,
VariablePrecisionIntegers/@vpi/floor.m,
VariablePrecisionIntegers/@vpi/full.m,
VariablePrecisionIntegers/@vpi/gcd.m,
VariablePrecisionIntegers/@vpi/ge.m,
VariablePrecisionIntegers/@vpi/gt.m,
VariablePrecisionIntegers/@vpi/isequal.m,
VariablePrecisionIntegers/@vpi/iseven.m,
VariablePrecisionIntegers/@vpi/isprime.m,
VariablePrecisionIntegers/@vpi/isunit.m,
VariablePrecisionIntegers/@vpi/iszero.m,
VariablePrecisionIntegers/@vpi/lcm.m,
VariablePrecisionIntegers/@vpi/le.m,
VariablePrecisionIntegers/@vpi/leadingdigit.m,
VariablePrecisionIntegers/@vpi/log.m,
VariablePrecisionIntegers/@vpi/log10.m,
VariablePrecisionIntegers/@vpi/log2.m,
VariablePrecisionIntegers/@vpi/lt.m,
VariablePrecisionIntegers/@vpi/minus.m,
VariablePrecisionIntegers/@vpi/mod.m,
VariablePrecisionIntegers/@vpi/mpower.m,
VariablePrecisionIntegers/@vpi/mrdivide.m,
VariablePrecisionIntegers/@vpi/mtimes.m,
VariablePrecisionIntegers/@vpi/nchoosek.m,
VariablePrecisionIntegers/@vpi/ne.m,
VariablePrecisionIntegers/@vpi/nthroot.m,
VariablePrecisionIntegers/@vpi/order.m,
VariablePrecisionIntegers/@vpi/plus.m,
VariablePrecisionIntegers/@vpi/power.m,
VariablePrecisionIntegers/@vpi/powermod.m,
VariablePrecisionIntegers/@vpi/prod.m,
VariablePrecisionIntegers/@vpi/quotient.m,
VariablePrecisionIntegers/@vpi/randint.m,
VariablePrecisionIntegers/@vpi/rdivide.m,
VariablePrecisionIntegers/@vpi/rem.m,
VariablePrecisionIntegers/@vpi/round.m,
VariablePrecisionIntegers/@vpi/shiftdec.m,
VariablePrecisionIntegers/@vpi/sign.m,
VariablePrecisionIntegers/@vpi/single.m,
VariablePrecisionIntegers/@vpi/sort.m,
VariablePrecisionIntegers/@vpi/sortrows.m,
VariablePrecisionIntegers/@vpi/sqrt.m,
VariablePrecisionIntegers/@vpi/sum.m,
VariablePrecisionIntegers/@vpi/times.m,
VariablePrecisionIntegers/@vpi/trailingdigit.m,
VariablePrecisionIntegers/@vpi/uminus.m,
VariablePrecisionIntegers/@vpi/unique.m,
VariablePrecisionIntegers/@vpi/uplus.m,
VariablePrecisionIntegers/@vpi/vpi.m,
VariablePrecisionIntegers/@vpi/vpi2base.m,
VariablePrecisionIntegers/@vpi/vpi2bin.m,
VariablePrecisionIntegers/@vpi/vpi2english.m,
VariablePrecisionIntegers/base2vpi.m,
VariablePrecisionIntegers/bin2vpi.m,
VariablePrecisionIntegers/binomfactors.m,
VariablePrecisionIntegers/catdigits.m,
VariablePrecisionIntegers/createPrimesList.m,
VariablePrecisionIntegers/demo_vpi.m,
VariablePrecisionIntegers/fibonacci.m,
VariablePrecisionIntegers/getprimeslist.m,
VariablePrecisionIntegers/html/demo_vpi.png,
VariablePrecisionIntegers/html/demo_vpi_01.png,
VariablePrecisionIntegers/html/demo_vpi_02.png,
VariablePrecisionIntegers/html/demo_vpi_03.png,
VariablePrecisionIntegers/html/demo_vpi_04.png,
VariablePrecisionIntegers/html/demo_vpi_05.png,
VariablePrecisionIntegers/html/demo_vpi_06.png,
VariablePrecisionIntegers/ispalindrome.m,
VariablePrecisionIntegers/iszero.m,
VariablePrecisionIntegers/legendresymbol.m,
VariablePrecisionIntegers/lineardiophantine.m,
VariablePrecisionIntegers/mersenne.m,
VariablePrecisionIntegers/minv.m,
VariablePrecisionIntegers/modrank.m,
VariablePrecisionIntegers/modroot.m,
VariablePrecisionIntegers/modsolve.m,
VariablePrecisionIntegers/nextprime.m,
VariablePrecisionIntegers/numberOfPartitions.m,
VariablePrecisionIntegers/quadraticresidues.m,
VariablePrecisionIntegers/quotient.m,
VariablePrecisionIntegers/ReadAboutVPI.rtf,
VariablePrecisionIntegers/subfactorial.m,
VariablePrecisionIntegers/totient.m
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (32)
11 Feb 2009 Husam Aldahiyat

vpi2english is the icing on the cake.

15 Feb 2009 Sebastian Randel

Great work!

21 Feb 2009 Petter

Indroducing new function names is inconvenient for the user, overloading existing ones is preferable.

11 Mar 2009 John D'Errico

In the first release, I had given new names to a few functions, like factorial, nchoosek, and prod. This allowed those functions to work on double inputs, yet still produce a vpi result. Petter makes a valid argument though, so I have changed that.

In this release, functions that already exist in matlab have been overloaded (along with a huge number of other enhancements.)

11 Mar 2009 Kevin

I don't understand the utility of this function.

Sure its neat to have hundreds of digits for some esoteric project, but what is the goal. Give an example of the usage of this tool suite. Is it to prove a theorem? Is it to design a new compression algorithm? Is it to simulate a fluid flow problem? What is the goal?

In my line of work, 3 significant digits is ALL we can ever hope for. With 4, we would be virtually guaranteed contract renewal for the next 5 years. But 100s of digits? C'mon.

Please explain WHY calculating 100 factorial to the final place is of any utility.

BTW, mathematica, maple and other symbolic programs have been able to do this for years.

12 Mar 2009 John D'Errico

Dear Kevin,

(Sigh.) Just because you personally don't ever need more than 3 digits in any computation does not mean that no one else will ever have such a need. And there is NO reason to trash the useful work of another just because your own point of view is so specialized.

This toolbox does not have a specific purpose. As a toolbox, it should NOT be so specialized that others cannot use it for their purposes. And as an author of dozens of toolboxes over the years, I am continually surprised at how others have used the utilities I've offered, in a variety of ways. But if you need a reason for something to exist, I'll offer a few such reasons.

Surely the most well publicized reason to work with large integers is public key encryption. Here one must find large prime numbers (with very many digits) and work with them.

http://en.wikipedia.org/wiki/RSA

On the other end of encryption is the task of breaking such a code. Here tools are needed to factor large integers. While the specific tool I've provided to factor integers is only capable of factoring integers with a few dozen digits with any regularity, it is far better than the very limited tools provided in MATLAB itself. I've also begun to work on other factoring tools, with the potential to solve larger factoring problems. Admittedly, the best such tools would use multiple CPUs in such a task, parcelling out the work. But, this is something that is easily done in the factoring of large integers. Read about the quadratic sieve methods for factoring.

http://en.wikipedia.org/wiki/Quadratic_sieve

These are very useful methods that can succeed in factoring huge numbers. Again, they require the ability to use multiple CPUs, all working in parallel, but this is something that is now becoming quite feasible. In fact, I've even written a simple working quadratic sieve factoring code, although it is far below the standards I put on my own work to release.

This toolbox is not (yet) capable of working with the speed necessary to factor numbers with several hundred digits. But it can serve as a useful testbed for algorithmic development in that field, and as an easy, inexpensive way to learn some techniques for such work.

Are there needs to work on the breaking of codes? Perhaps World War II might have lasted a bit longer had those mathematicians working with Alan Turing not done their jobs. Read about codes and cyphers.

http://www.codesandciphers.org.uk/

The National Security Agency is one such place where many mathematicians work.

http://www.nsa.gov/CAREERS/

If this set of tools existed for no reason other than primality testing and factoring, I'd suggest it has some merit. But there are other tools I've provided inside that may offer value. Solutions of linear Diophantine equations are frequently requested on the newsgroup, so I added a simple tool to do so. It is one that I will look to improve (given time) with future releases. As well I've begun work on Pell equation solvers. These last tools are of interest to number theorists, so perhaps they are boring to you. All of them tend to use continued fraction approximations to numbers, approximations to fractions, approximations to square roots, etc. Number theory is itself a topic that offers careers to mathematicians worldwide.

http://en.wikipedia.org/wiki/Number_theory

As well, number theory is perhaps one of the prettiest branches of mathematics. It offers a way for a student to become interested in mathematics, with easily formulated problems with correspondingly beautiful solutions.

In my own case, I spent my first several years as a student mostly interested in number theory, before gravitating to more prosaic fields like numerical analysis, statistics, modeling and applied mathematics in general. A student who becomes entranced with mathematics, playing with such an easily formulated problem like Goldbach's conjecture, may then move into other fields of mathematics, perhaps knot theory, differential or algebraic geometry, statistics, or even diverge into some branch of engineering. And the fact is, I've had the need for results from diverse fields of mathematics in my career as a consulting mathematician.

You state that other tools exist that can serve the same purposes as this toolbox, i.e., Maple and Mathematica. While they do exist, and serve that purpose very well, not every individual has the money to pay for those tools. For example, I don't own the symbolic toolbox, nor a copy of Mathematica. For those individuals with an interest in the problems this toolbox can solve, they can do their work for no additional investment.

Finally, this toolbox can serve to teach others methods they can use to build their own toolboxes, a template of sorts. Alternatively, one could easily expand these tools to work with variable precision floating point arithmetic, or with fractions of arbitrary size. When enough people have the current matlab releases, I'll convert this toolbox to use the newer methods now found in matlab for working with classes and OOP code.

So I am truly sorry that this tool is of no interest to you. But that only says what limited horizons you live within. Just for once, expand those horizons. Learn some mathematics.

John

13 Mar 2009 Derek O'Connor

Dear Kevin,

Please calculate the average of the following set of 7680 floating point numbers to 3 "significant" digits.

https://hpcrd.lbl.gov/SCG/ocean/NRS/etaana.dat

Please post your result and tell us how you did it.

Yours sincerely,

Derek O'Connor

13 Mar 2009 Orlando Rodríguez

What a marvelous tool! Thank you John!

13 Mar 2009 Kenneth Eaton  
14 Mar 2009 Omid Khanmohamadi

Dear Kevin,

You "don't understand the utility of this function"? First of all, this submission is not a function, it's a toolbox. I suggest you read John's reply to get a glimpse of its utility, but even before that I suggest, as he did, that you learn some mathematics. That might help you to understand the utility of this toolbox, his other submission MIN2, MAX2, whose utility, too, you have had trouble understanding, and many other of his submissions for that matter - before you go around commenting on their utility. And after that, I suggest you go through the code. I'm sure you can learn one or two things about MATLAB.

Omid

PS. As always, great submission John. Thanks for sharing this with the community.

23 Mar 2009 Alain Barraud

vpi is an excellent toolbox, thanks a lot.
I shoud add a comment to derek O Coonor question. I have found 4.661273948537807e-005 as the mean of the data in "etaana" without any toolbox just using floating poitn computation within Matlab. I have used a function I have written some years ago which computes full precision sums of any condition number (here 1.5e17) in a very simple and efficient way.

23 Mar 2009 Derek O'Connor

Dear Alain,

Thanks for your reply and correct answer mean(x) = 4.661273948537807e-005, (or
sum(x) = 7680*4.661273948537807e-005 = 0.3579858392477036 (16 digits) )
which is the mean of the data at https://hpcrd.lbl.gov/SCG/ocean/NRS/etaana.dat.

I meant to ask for the sum(x) not mean(x) because this sum(x) was discussed in
the paper by Yun He and Chris H.Q. Ding, ``Using Accurate Arithmetics
to Improve Numerical Reproducibility and Stability in Parallel Applications'',
Journal of Supercomputing, Vol 18, No 3, Mar 2001.

 http://crd.lbl.gov/~yunhe/papers/HPA_JSC.pdf

In what follows the 7680 d.p.f.p. numbers in etaana.dat are stored in ssh.mat

They give exact sum(ssh) = 0.35798583924770355224609375 (26 digits).

I think you should publish your code and also how the condition of any sum(x)
can be calculated. I have met many people who are surprised that a
simple summation can give very bad results.

Matlab gives sum(ssh) = 3.441476821899414e+001, which has a relative error
of 9.513444009773050e+001, nearly 2 orders of magnitude wrong.

Using the 1-norm my condition number for sum(ssh) is
k_1 = n*sumexact(abs(ssh))/abs(sumexact(ssh)) ~ 10^21.

If I use the Matlab sum (ssh) I get k_1 ~ 10^16,
which is not correct but still gives a warning that
this problem is very ill-conditioned.

Here is my Matlab implementation of D. Priest's method,
which gives the correct result, rounded to about 16 digits :

===========================================================
function snew = SumP(xorig);

% Using Douglas M. Priest's thesis recommendation.
% D.M. Priest: "On properties of floating point arithmetics:
% Numerical stability and the cost of accurate computations",
% Mathematics Department,
% University of California at Berkeley, CA, USA (1992).

% This function has complexity O(n log n) because of the sort.
% This is the price we pay to get the correct sum.

% Written by Derek O'Connor March 2006.

% --- Sort xorig in decreasing abs(x) order

    [absx absord] = sort(abs(xorig),'descend');
    x = xorig(absord); % |x1| >= |x2| >= ... >= |xn|

% --------- Compensated Summation --------
    sold = x(1);
    c = 0;
    for k = 2:length(x)
       y = x(k) + c;
       snew = sold + y;
       u = snew - sold;
       c = y - u;
       sold = snew;
    end;
% --------- end of SumP -----------------

============================================================

Here is the result using Priest's method:

>> SumP(ssh)
ans =
    3.579858392477036e-001

Here is the result using Rump's Intlab 5.5 set to 30-digit precision:

>> p = 30; display(SumRump(ssh,p),p)
long ans =
  3.579858392477035522460937500000 * 10^-0001

It seems that this Sea Surface Heights problem needs at least 26-digit
precision to obtain the exact sum.

Intlab is here : http://www.ti3.tu-harburg.de/rump/intlab/

Regards,

Derek O'Connor

24 Mar 2009 Bill McKeeman

I am impressed the scope and presentation of this toolbox. Very nice work. I have a couple of nits to comment upon.
The last example in vpi.m seems to have lost its text.
I recommend that the examples be such that, if cut and pasted to the command line, run. I did this with my World Time Zones FX entry in response to a criticism and was pleased at the result.
I experimented with replacing
 INT.digits = double(fliplr(N))-48;
with
  INT.digits = int8(fliplr(N))-int8('0');
The package still seems to run and takes 8x less storage for the vpi numbers.

24 Mar 2009 John D'Errico

Thanks Bill. I'll fix the examples, and look into the question of changing the internal storage format. It is something I've considered before. My initial reason for leaving them all as doubles internally was to get the maximum speed. I want to minimize the number of events where I need to force a type conversion between int and double.

24 Mar 2009 John D'Errico

I've done a more careful investigation into the question. Can I in fact use an integer format for the internal storage?

As it turns out, I cannot do so, at least not without seriously compromising the capabilities of this toolbox. First, the question is, can I use INT8 for storage? The answer here is no. While Bill checked to see if it would work, he apparently did not do a multiply between a pair of vpi numbers. vpi uses a nice trick to multiply a pair of vpi numbers. It uses conv, whereby it gains a massive increase in its multiplication speed. And since multiplication is necessary for these tools, the loss of conv would be rather bad for performance.

Sadly, conv does not support int8 inputs. Even worse, int8 would cause a dramatic restriction on the size of the numbers that vpi can handle. try this simple test:

N = [9 9];
conv(N,N)
ans =
    81 162 81

So were I to store the number 99 as a vpi number that uses int8 as a storage mechanism, then I could not actually multiply 99*99 using conv, even if int8 was supported as an input to conv. The conv result would overflow int8 storage.

This suggests an alternative. Perhaps I could use single as the internal storage for the digits. In fact, this offers some minor gain. Use of single would cut the memory requirements for vpi numbers in half. Even better, in my tests the single operations on integers are actually a bit faster than they are for doubles.

So for a few moments, I thought I could at least use single. The problem is, it too will cause a problem. This would limit vpi number to about a maximum of roughly 100,000 digits. Again, the problem is numeric overflow in multiplication using conv. While numbers that large might seem large, I'd still prefer to have essentially no limit on the number of digits.

One other option is to use a smaller form for storage, but then to automatically convert from int8 to doubles and then back (internally) for all operations. I could do this, but it seems risky, and likely to cause bugs.

So for the present time, I'm forced to stick with the internal storage as it is.

01 Apr 2009 Giampiero Campa

very cool,
however i think there's something wrong with line 129 of the demo:
>> iseven(2^127)
it should not be just a double, and yet is too large to be a vpi ...
it gives an error in r2009a anyway.

perhaps you meant iseven(vpi(2)^127) ...
Giampy

02 Apr 2009 John D'Errico

Sorry. I'll fix the demo.

15 Apr 2009 Andreas Bonelli

Great submission, but there seems to be a bug with vpi2english for numbers from 1 to 99:

>> vpi2english(vpi('1'))
??? Index exceeds matrix dimensions.

Error in ==> vpi.vpi2base at 114
    B(i) = base2dec(fliplr(cdigits(ind)),10);

Error in ==> vpi.vpi2english at 53
base1000 = vpi2base(N,1000);

15 Apr 2009 Andreas Bonelli  
15 Apr 2009 John D'Errico

I just uploaded a new release, fixing the bug in vpi2english.

23 Apr 2009 Lissa  
19 May 2009 Neha P

Dear Errico,

The tool box you have created in order to store large integer numbers has been very helpful for our project. Currently we have encountered a problem to store large floating numbers.
I would request you to give me any information regarding the above problem.

14 Jul 2009 Ben Petschel

John, you've done a great service to the mathematical community (esp. number theorists and Project Euler enthusiasts!)

In the vpi/add carry operation you could improve the performance of pathological cases such as 1+vpi(repmat('9',1,1e6)) by changing the while loop to a for loop.

14 Jul 2009 John Edwards

Hi John,

I am a beginner with Matlab. However, your creation caught my eye and I downloaded the package. I used very simple examples but MATLAB kept returning the same error:
---------------------------------
A = vpi(17)^17
??? lseif ~ischar(N) &&
                    |
Missing variable or function.

Syntax error in ==> C:\MATLABR11\toolbox\VariablePrecisionIntegers\@vpi\vpi.m
On line 51 ==> elseif ~ischar(N) && ~isnumeric(N)
----------------------------

I am not sure how to resolve this error. Any ideas?

Thanks

John Edwards

14 Jul 2009 John D'Errico

John - I think the problem is shown by your path. Are you using an older release of MATLAB? Perhaps release 11? If so, I'll not be at all surprised at seeing a problem. I would not expect vpi to run on older versions, and I have not tested it there.

If you actually have a more recent release, then please contact me via mail and I will help to resolve the problem.

14 Jul 2009 John D'Errico

Ben - I've submitted an update, that now handles the pathological cases for plus and times.

22 Jul 2009 Gwendolyn Fischer

Hi John,
I like your submission, and it works fine for my puposes even in R14. Using your old factor routines, as the new factor command uses a mat file (_primeslist_), which the old matlab version can not read. Is it possible to provide a compatible mat file for MATLAB R14?

Thanks

22 Jul 2009 John D'Errico

Hi Gwendolyn,

I was going to submit a new version today again. The simplest thing to do is to save that file in a form that is compatible with older releases that go back to version 7.

John

29 Jul 2009 Khaled Hamed

Another good reason to use higher preciesion: the famous subtractive cancellation error

>> x=77617;y=33096;z=33375*y^6+100*x^2*(11*x^2*y^2-y^6-121*y^4-2)+550*y^8

z = -1.5112e+023

>> x=sym(77617);y=sym(33096);z=33375*y^6+100*x^2*(11*x^2*y^2-y^6-121*y^4-2)+550*y^8

z = -200

>>x=vpa(77617);y=vpa(33096);z=100*x^2*(11*x^2*y^2-y^6-121*y^4-2)+33375*y^6+550*y^8
 
z = -200.0

>> x=vpi(77617);y=vpi(33096);z=33375*y^6+100*x^2*(11*x^2*y^2-y^6-121*y^4-2)+550*y^8

z = -200

vpi is as accurate as symbolic and vpa, roughly four times faster than sym and eight times faster than vpa

06 Aug 2009 Khaled Hamed

More fun with vpi2english if you use, for example,

speak(vpi2english(vpi(2^52)))

The function "speak" is summission File ID: #4769 named "Speak".

There are a also a couple more "speak" submissions around.

22 Nov 2009 Derek O'Connor

John,

The demo_vpi.m needs your consolidator function:

http://www.mathworks.com/matlabcentral/fileexchange/8354-consolidator

Great package.

Derek O'Connor

22 Nov 2009 John D'Errico

Sorry about that. Only the binomfactors code uses consolidator, and only nchoosek calls binomfactors. I never caught it in testing, since consolidator is on my search path.

Anyway, and would be more efficient to use a call to unique there, then accumarray anyway, since no tolerance is employed.

I've submitted a new release. It will be there on Monday morning.

Please login to add a comment or rating.
Updates
20 Jan 2009

I've added GCD and LCM, plus the first release was missing rdivide, which is now included.

23 Jan 2009

Repaired a bug in mod and quotient, plus improved the speed of mod. Added new functionality, prime number tests, also the powermod function.

26 Jan 2009

Added much additional functionality, especially factoring of vpi numbers. Also expanded the demos. Minor bugs cleaned up, documentation cleanup performed.

27 Jan 2009

Added a ReadMe file, plus some new functionality - sqrt, log, log2, log10.

02 Feb 2009

Added an exponential computation, yielding the integer part of exp(x) for vpi inputs x. More demos too.

09 Feb 2009

Added functionality to sqrt (useful for factoring large integers)

Enhanced display, now properly names the variable on the command line.

Continual improvements to factor.

10 Feb 2009

Inclusion of tools for quadratic residues, Legendre symbols. Also a utility to write out a number as readable text.

11 Feb 2009

Extended vpi2english up to 123 digit numbers.

20 Feb 2009

Minor repairs applied to several functions - vpi, power, factor, primality, vpi2base, vpi2english.

vpi2englich was greatly extended in its domain.

New functions - modroot, multiplicativeinverse, totient, legendresymbol, randint, ne, nthroot.

11 Mar 2009

MANY updates made, and many new functions included. Arrays and vectors of vpi objects are now supported.

22 Mar 2009

Improved (by a factor of over 5) factoring speed, as well as improvements in a few other operations, such as gcd and isprime.

10 Apr 2009

Repaired a problem when a vpi number is multiplied by (or is added to) a non-integer float.

Also added the nextprime function.

15 Apr 2009

Repaired vpi2english bug (actually a bug in vpi2base)

16 Apr 2009

Fixed a bug in rdivide

22 Apr 2009

A speed fix. This new release is approximately twice as fast when adding large numbers, and more so when multiplying large numbers, or a double times a large number.

23 Apr 2009

A new tool to return or set the digits of a vpi number directly. ispalindrome, a test for palindromicity. Also a function to compute the factors of a large binomial coefficient. This improves the speed for nchoosek.

27 Apr 2009

Fixed a bug in sqrt, so it works properly on arrays of inputs. Added the full function for vpi, which does nothing except allow meshgrid and ndgrid to work with no modifications.

06 May 2009

New tools: shiftdec, fibonacci. Shiftdec speeds up some multiply and divide actions considerably. Found/repaired another bug in sqrt for arrays of elements.

14 Jul 2009

New functions (subfactorial, etc.) Also sped up plus and times for better carry behavior for pathological cases.

20 Jul 2009

The only change today is to include Ben Petchel's code for unique and sortrows. Thanks!

22 Jul 2009

Repair to factor, to better handle numbers with many replicated small factors. (Also fixed a bug there.) Also added the ability to generate the _primeslist_.mat file for older releases of matlab.

29 Oct 2009

Now stores the list of primes below 2^26 in a compressed uint8 form. This saves about 8MB of space, plus it will load the file faster when needed.

22 Nov 2009

There was one place where a call to consolidator was used. Replaced it by the simpler combination of a call to unique, then accumarray. This will be more efficient here anyway.

Tag Activity for this File
Tag Applied By Date/Time
digits John D'Errico 20 Jan 2009 15:20:27
integer John D'Errico 20 Jan 2009 15:20:27
arbitrary precision John D'Errico 20 Jan 2009 15:20:27
multiple precision John D'Errico 20 Jan 2009 15:20:27
variable precison John D'Errico 20 Jan 2009 15:20:27
precision John D'Errico 20 Jan 2009 15:20:27
arithmetic John D'Errico 20 Jan 2009 15:20:27
toolbox John D'Errico 20 Jan 2009 15:20:27
numbers John D'Errico 20 Jan 2009 15:20:27
type John D'Errico 20 Jan 2009 15:20:27
data type John D'Errico 20 Jan 2009 15:20:27
prime John D'Errico 23 Jan 2009 14:46:34
primality John D'Errico 23 Jan 2009 14:46:34
mersenne John D'Errico 23 Jan 2009 14:46:34
millerrabin John D'Errico 23 Jan 2009 14:46:34
fermat John D'Errico 23 Jan 2009 14:46:34
lucaslehmer John D'Errico 23 Jan 2009 14:46:34
factor John D'Errico 26 Jan 2009 15:50:07
factoring John D'Errico 26 Jan 2009 15:50:07
lucas John D'Errico 26 Jan 2009 15:50:07
lehmer John D'Errico 26 Jan 2009 15:50:07
miller John D'Errico 26 Jan 2009 15:50:07
rabin John D'Errico 26 Jan 2009 15:50:07
toolbox Cristina McIntire 28 Jan 2009 10:20:40
data Cristina McIntire 28 Jan 2009 10:20:40
potw Shari Freedman 20 Apr 2009 12:34:52
projecte John D'Errico 27 Apr 2009 11:13:07
biginteger John D'Errico 06 May 2009 13:39:20
 

MATLAB Central Terms of Use

NOTICE: Any content you submit to MATLAB Central, including personal information, is not subject to the protections which may be afforded information collected under other sections of The MathWorks, Inc. Web site. You are entirely responsible for all content that you upload, post, e-mail, transmit or otherwise make available via MATLAB Central. The MathWorks does not control the content posted by visitors to MATLAB Central and, does not guarantee the accuracy, integrity, or quality of such content. Under no circumstances will The MathWorks be liable in any way for any content not authored by The MathWorks, or any loss or damage of any kind incurred as a result of the use of any content posted, e-mailed, transmitted or otherwise made available via MATLAB Central. Read the complete Terms prior to use.

Contact us at files@mathworks.com