Code Monkey home page Code Monkey logo

delphibignumbers's Introduction

BigNumbers

BigInteger, BigDecimal and BigRational for Delphi

These are implementations of the multi-precision BigInteger, BigDecimal and BigRational types, built from scratch.

BigInteger

BigInteger is a multi-precision integer. Its size is only limited by available memory.

BigInteger is built for ease of use, speed and reliability. It is written in plain Object Pascal and x86-32/x86-64 assembler, but every assembler function has a so called "pure Pascal" equivalent as well. It is modelled after the BigInteger type in .NET, but is far more optimized than that and provides an interface that is more in line with Delphi. It uses higher level algorithms like Burnikel-Ziegler, Karatsuba, Toom-Cook, etc. to make things fast even for very large integers. It offers overloaded operators and all the usual functions. More information can be found on the BigIntegers unit page on my website.

BigDecimal

BigDecimal is a multi-precision decimal floating point type. It can have an almost unlimited precision.

BigDecimal is equally built for ease of use and reliability. It builds on top of BigInteger: the internal representation is a BigInteger for the significant digits, and a scale to indicate the decimals. It also offers overloaded operators and all the usual functions. This is modelled after the BigDecimal type in Java, but the interface is more in line with Delphi. More information about this type can be found on the BigDecimals unit page on my website.

BigRational

A type that holds a number as fraction (ratio) of two BigIntegers, a numerator and a denominator, i.e. 1/7 or 100/3. This type is very good at simple arithmetic (+, -, *, /), since it doesn't lose precision or need any rounding. Still a work in progress...

C++Builder

The newest version of BigIntegers has additional overloaded operators and additional constructors that are compatible with C++Builder. So now you simply include:

#include "Velthuis.BigIntegers.hpp"

and then you can do things like:

BigInteger a = 17;
BigInteger b = "123";
BigInteger c = a + b;

Directory structure

BigNumbers
   DataGenerators
      BigDecimals
         BigDecimalTestDataGenerator /...       --- Test data generator in Java; 
	                                            open with NetBeans 8
      BigIntegers
         BigIntegerTestGenerator /...           --- Test data generator in C#; open .sln file with 
                                                    Visual Studio 2010 (Express) or newer
	 Java/BigIntegerTestDataGenerator /...  --- Newer test data generator in Java; 
	                                            open with NetBeans 8
      BigRationals                                   
         BigRationalTestDataGenerator /...      --- Test data generator in Java, using the Apache 
                                                    Commons-Math library.
                                                    Open with NetBeans 8. Might require installation 
                                                    of the Apache libs.
   Source                                       --- Sources for units and for bases.inc generator
   Tests
      BigDecimals /...                          --- Sources for DUnit tests for BigDecimals
      BigIntegers /...                          --- Sources for DUnit tests for BigIntegers
      BigRationals /...                         --- Sources for DUnit tests for BigRationals
   Visualizers                                  --- Sources for IDE debug visualizer DLL and packages for BigInteger 
                                                    and BigDecimal   

delphibignumbers's People

Contributors

rvelthuis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

delphibignumbers's Issues

Tryng to calculate modulus, dies after correct result into FastMM error

We use latest Delphi(10.2 Tokyo and latest FastMM4

Code is following

function BigIntegerStrMod(const ABigInteger: string; const Adivider: Integer): Integer;
var
LBigInt: BigInteger;
LDivisor: BigInteger;
LReminder: BigInteger;
begin
// Alkuarvo
if not BigInteger.TryParse(ABigInteger, LBigInt) then
raise Exception.CreateFmt('Virheellinen numero %s', [ABigInteger]);
LDivisor := BigInteger.Create(Adivider);
LReminder := BigInteger.Create(0);

// Lasketana ja Palautetaan
LReminder := LBigInt mod LDivisor;
Result := LReminder.AsInteger;
end;

At last line when some cleanup happens we get FastMM error


STCommon.UnitTests.exe: Memory Error Detected

FastMM has detected an error during a FreeMem operation. The block footer has been corrupted.

The block size is: 40

This block was allocated by thread 0x54E8, and the stack trace (return addresses) at the time was:

43BDFA [FastMM4][DebugAllocMem$qqri]

409C86 [System.pas][System][AllocMem$qqri][4688]

E2E558 [Velthuis.BigIntegers.pas][Velthuis.BigIntegers][Bigintegers.AllocNewMagnitude$qqrrpvi][9265]

E2E5A5 [Velthuis.BigIntegers.pas][Velthuis.BigIntegers][Bigintegers.BigInteger.MakeSize$qqri][9274]

E2AF40 [Velthuis.BigIntegers.pas][Velthuis.BigIntegers][Bigintegers.BigInteger.TryParse$qqrx20System.UnicodeStringzcr31Velthuis.Bigintegers.BigInteger][5190]

409CBA [System.pas][System][@getmem$qqri][4745]

E2AE55 [Velthuis.BigIntegers.pas][Velthuis.BigIntegers][Bigintegers.BigInteger.TryParse$qqrx20System.UnicodeStringr31Velthuis.Bigintegers.BigInteger][5171]

4105E6 [System.pas][System][@FinalizeArray$qqrpvt1ui][32099]

4104A1 [System.pas][System][@FinalizeRecord$qqrpvt1][31777]

E33CE0 [STCommon.PankkiUtils.pas][STCommon.PankkiUtils][Pankkiutils.BigIntegerStrMod$qqrx20System.UnicodeStringxi][1075]

E33F01 [STCommon.PankkiUtils.pas][STCommon.PankkiUtils][Pankkiutils.TarkistaRFViite$qqrx20System.UnicodeString][1127]

The block is currently used for an object of class: Unknown

The allocation number is: 589545

The block was previously freed by thread 0x54E8, and the stack trace (return addresses) at the time was:

43BD75 [FastMM4][DebugReallocMem$qqrpvi]

409CF7 [System.pas][System][@ReallocMem$qqrrpvi][4867]

40FB19 [System.pas][System][@UStrSetLength$qqrr20System.UnicodeStringi][29850]

40FB9A [System.pas][System][@UStrCat$qqrr20System.UnicodeStringx20System.UnicodeString][29963]

E33C4D [STCommon.PankkiUtils.pas][STCommon.PankkiUtils][Pankkiutils.RFReferenceCharsToNumbers$qqrx20System.UnicodeString][1064]

E33E5C [STCommon.PankkiUtils.pas][STCommon.PankkiUtils][Pankkiutils.NormalizeRFReference$qqrr20System.UnicodeString][1096]

E33EDA [STCommon.PankkiUtils.pas][STCommon.PankkiUtils][Pankkiutils.TarkistaRFViite$qqrx20System.UnicodeString][1120]

4105D5 [System.pas][System][@FinalizeArray$qqrpvt1ui][32070]

E3BD9D [STCommon.PankkiUtils.DUnitX.pas][STCommon.PankkiUtils.DUnitX][Pankkiutils.Dunitx.TSTCommonPankkiUtilsTests.TarkistaRFViiteTest$qqrx20System.UnicodeStringxo][47]

4B6810 [System.Rtti.pas][System.Rtti][Rtti.RawInvoke$qqrpvp23System.Rtti.TParamBlock][7750]

4B6C14 [System.Rtti.pas][System.Rtti][Rtti.Invoke$qqrpvx42System.%DynamicArray$18System.Rtti.TValue%24System.Typinfo.TCallConvp24System.Typinfo.TTypeInfooo][7972]

The current thread ID is 0x54E8, and the stack trace (return addresses) leading to this error is:

411A1C [System.pas][System][@DynArrayClear$qqrrpvpv][35224]

4105E6 [System.pas][System][@FinalizeArray$qqrpvt1ui][32099]

4104A1 [System.pas][System][@FinalizeRecord$qqrpvt1][31777]

4105C5 [System.pas][System][@FinalizeArray$qqrpvt1ui][32058]

E33D58 [STCommon.PankkiUtils.pas][STCommon.PankkiUtils][Pankkiutils.BigIntegerStrMod$qqrx20System.UnicodeStringxi][1083]

E33F01 [STCommon.PankkiUtils.pas][STCommon.PankkiUtils][Pankkiutils.TarkistaRFViite$qqrx20System.UnicodeString][1127]

E3BD9D [STCommon.PankkiUtils.DUnitX.pas][STCommon.PankkiUtils.DUnitX][Pankkiutils.Dunitx.TSTCommonPankkiUtilsTests.TarkistaRFViiteTest$qqrx20System.UnicodeStringxo][47]

4B6810 [System.Rtti.pas][System.Rtti][Rtti.RawInvoke$qqrpvp23System.Rtti.TParamBlock][7750]

4B6C14 [System.Rtti.pas][System.Rtti][Rtti.Invoke$qqrpvx42System.%DynamicArray$18System.Rtti.TValue%24System.Typinfo.TCallConvp24System.Typinfo.TTypeInfooo][7972]

4ADAA5 [System.Rtti.pas][System.Rtti][Rtti.TRttiInstanceMethodEx.DispatchInvoke$qqrrx18System.Rtti.TValuepx18System.Rtti.TValuexi][5883]

4B6FBF [System.Rtti.pas][System.Rtti][Rtti.TRttiMethod.Invoke$qqrp14System.TObjectpx18System.Rtti.TValuexi][9212]

Current memory dump of 256 bytes starting at pointer address 7EF84C30:

00 00 00 00 08 00 00 00 D1 D6 39 E5 57 28 D4 21 5A 80 29 00 00 00 00 00 00 00 00 00 00 00 00 00

00 00 00 00 00 00 00 00 00 00 00 00 80 80 80 80 80 80 80 80 80 80 80 80 00 00 00 00 10 11 F8 7E

00 00 00 00 00 00 00 00 14 BA 43 00 00 00 00 00 66 FD 08 00 BA 9C 40 00 6B C7 40 00 8A CF 40 00

DF 40 5E 00 74 C7 40 00 69 45 41 00 26 3F 5E 00 88 9E 5E 00 B2 9F 5E 00 28 33 41 00 D1 91 5F 00

E8 54 00 00 E8 54 00 00 89 C7 40 00 D5 CF 40 00 94 01 53 00 03 C9 40 00 04 4E 52 00 9C 65 52 00

F1 50 52 00 8B F6 75 00 A0 52 76 00 F6 4E 52 00 22 4A 52 00 34 00 00 00 AC 9A 4F 00 27 55 91 86

34 12 5E 00 00 00 00 00 01 00 00 00 34 0F 5E 00 90 40 5E 00 F0 4C F8 7E 9C 40 5E 00 F0 4C F8 7E

70 E4 FB 7E DC 94 E5 00 00 00 00 00 00 00 00 00 00 00 00 00 D8 AA 6E 79 00 00 00 00 10 11 F8 7E

. . . . . . . . Ñ Ö 9 å W ( Ô ! Z € ) . . . . . . . . . . . . .

. . . . . . . . . . . . € € € € € € € € € € € € . . . . . . ø ~

. . . . . . . . . º C . . . . . f ý . . º œ @ . k Ç @ . Š Ï @ .

ß @ ^ . t Ç @ . i E A . & ? ^ . ˆ ž ^ . ² Ÿ ^ . ( 3 A . Ñ ‘ _ .

è T . . è T . . ‰ Ç @ . Õ Ï @ . ” . S . . É @ . . N R . œ e R .

ñ P R . ‹ ö u .   R v . ö N R . " J R . 4 . . . ¬ š O . ' U ‘ †

4 . ^ . . . . . . . . . 4 . ^ . � @ ^ . ð L ø ~ œ @ ^ . ð L ø ~

p ä û ~ Ü ” å . . . . . . . . . . . . . Ø ª n y . . . . . . ø ~


OK

And then exception


Debugger Exception Notification

Project STCommon.UnitTests.exe raised exception class EInvalidPointer with message 'Invalid pointer operation'.

Break Continue Help

Is My Code broken, is there something I need to do etc...

Possibly wrong date format

Velthuis.BigDecimals.pas

LongDateFormat: 'dddd, dd MMMMM yyyy HH:mm:ss';

maybe to

LongDateFormat: 'dddd, dd MMMMM yyyy HH:nn:ss';

Months in time part seems wrong. (If more than less standard Delphi format(s))

not thread-safe

using in multithread programs failes due to usage of global unsafe variables

Wrong Round?

Hello, i test BigInteger and saw a mismatch.
Code

C := GetTickCount;
_BigInteger.RoundingMode := rmRound;
for I := 0 to Iteration do
begin
_Double := I / 100;
_BigInteger := BigInteger.Create(_Double);
_Int64 := Round(_Double);
if _Int64 <> _BigInteger then
begin
S := 'Extended=' + _Double.ToString + ' ,Int64= ' + _Int64.ToString +
' BigInteger=' + _BigInteger.ToString + ' Error';
Memo1.Lines.Add(S);
Break;
end;

end;
C := GetTickCount - C;
Memo1.Lines.Add(C.ToString);

result:

Extended=1,5 ,Int64= 2 BigInteger=1 Error

In bigintegers.pdf

rmRound

Rounds the same way as theSystem.Round function. Any (absolute) fraction > 0.5 (this excludes 0.5 itself) is roundedaway from 0. So 1.5 rounds to 1, but 1.50001 rounds to 2.

But its not equally System.Round (bank rounding).
How Round similar System.Round (bank rounding)?

Error in BigIntegers.Primes

I'm getting an error when attempting to compile velthuis.bitintegers.primes on the function NextProbablePrime. Errors on BigInteger.Two.

You have a global variable "Two" declared as a BigInteger, and initialize it to 2, and you also have a local variable Two also declared as a BigInteger. But BigInteger class does not have a method Two.

FreePascal Support

First of all, I would like to commend the brilliant work you have done on this library.
I would also like to ask if there are any future plans to support FreePascal compiler??

Velthuis.BigIntegers.Primes Problem

Your BigInteger Package has a problem.

On the Velthuis.BigIntegers.Primes unit

// Next probable prime> = N.
Function NextProbablePrime (const N: BigInteger; Precision: Integer): BigInteger;
Var
   Two: BigInteger;
Begin
   Result: = N;
   If Result = BigInteger.Two then
     Exit;
   If Result.IsEven then
     Result: = Result.FlipBit (0);
   While not IsProbablePrime (Result, Precision)
   Begin
     Result: = Result + BigInteger.Two;
   End;
   Result: = N;
End;

[Dcc32 Error] Velthuis.BigIntegers.Primes.pas (191): E2003 Undeclared identifier: 'Two'

BigDecimal.Sqrt always gets divide by zero error.

I love Bigintegers and BigDecimals!

I can't get BigDecimal.Sqrt to work: always get divide by zero error. Here is my humble attempt:
A := '123.456';
writeln('>> 1 ',A.ToPlainString);
B := BigDecimal.Sqrt(A);
writeln('>> 2');
--- Of course A and B are type BigDecimal. I must be doing something wrong. The same code for BigInteger works fine.

After a little digging:
I changed Veltius.BigDecimals.pas, function BigDecimal.Sqrt(Precision: Integer): BigDecimal;
from:
while (Result * Result - Self).Abs >= Epsilon do
to:
while ((Result * Result - Self).Abs >= Epsilon) and (Result < 0.0)

This seems to work for me.

A rare error when parsing huge integers

Hi,
I am writing a faster parser function than the original one and while testing it I raised up an error that may be reproduce with this code:

procedure AParsingError;
var
  N,M : BigInteger;
  R : IRandom;
begin
  R := TDelphiRandom.Create(-332888001);
  N := BigInteger.Create(Random(100)*1000, R);
  BigInteger.Base := 12;
  M := BigInteger.Parse(N.ToString);
  if (N<>M) then raise Exception.Create('Parsed value differs from the original!');
end;

The N.ToString and M.ToString differs per the digits from positions 1983 to 1992 (probabely a Limb).
In attached file uBadValue.zip
there is a unit file embeding the value produced by the random generator (18250 hex-digits long), just in case.

Best regards,
F. MARQUES

Wrong exception message if calculate Sqrt of negative number

SNegativeRadicand contains "%s", so replace
raise EInvalidArgument.Create(SNegativeRadicand);
with
raise EInvalidArgument.CreateFmt(SNegativeRadicand, ErrorInfo);
in
class procedure BigInteger.Error(ErrorCode: TErrorCode; const ErrorInfo: array of const);
begin
case ErrorCode of
ecParse:
raise EConvertError.CreateFmt(SErrorParsingFmt, ErrorInfo);
ecDivbyZero:
raise EZeroDivide.Create(SDivisionByZero);
ecConversion:
raise EConvertError.CreateFmt(SConversionFailedFmt, ErrorInfo);
ecOverflow:
raise EOverflow.Create(SOverflow);
ecInvalidArgFloat:
raise EInvalidArgument.CreateFmt(SInvalidArgumentFloatFmt, ErrorInfo);
ecInvalidBase:
raise EInvalidArgument.Create(SInvalidArgumentBase);
ecInvalidArg:
raise EInvalidArgument.CreateFmt(SInvalidArgumentFmt, ErrorInfo);
ecNoInverse:
raise EInvalidArgument.Create(SNoInverse);
ecNegativeExponent:
raise EInvalidArgument.CreateFmt(SNegativeExponent, ErrorInfo);
ecNegativeRadicand:
raise EInvalidArgument.Create(SNegativeRadicand);
else
raise EInvalidOp.Create(SInvalidOperation);
end;
end;

Results of Divide, Sqrt etc. for precise numbers is zero

Happens if BigDecimal.DefaultPrecision is less then number precision.
If default precision is 64 then BigDecimal.Sqrt of number with 65 or more digits return always 0. "Sqrt(Pi) = 0"

Workaround:
call Sqrt with parameter Max(DefaultPrecision and Number.Precision)

The same problem is for division.
Happens for 10000 digit precison constants i.e. "Pi / 2 = 0"
if Pi decimal places >DefaultPrecision

Maybe it is a feature? :-)

Range check error

Happens in GetExponent functions only if range checking is on.

Solution:
replace
Result := E - CDoubleBias
with
Result := Integer(E) - Integer(CDoubleBias)
in FloatUtils.pas

function GetExponent(const AValue: Single): Integer; overload;
var
M, E: UInt32;
begin
M := GetRawSignificand(AValue);
E := GetRawExponent(AValue);
if (0 < E) and (E < CSingleExponentMask) then
Result := Integer(E) - Integer(CSingleBias)
else if E = 0 then
if M = 0 then
// +/- Zero
Result := 0
else
// Denormal
Result := 1 - CSingleBias
else
// NaN or +/-Infinity
Result := 0;
end;

function GetExponent(const AValue: Double): Integer; overload;
var
M: UInt64;
E: UInt32;
begin
M := GetRawSignificand(AValue);
E := GetRawExponent(AValue);
if (0 < E) and (E < CDoubleExponentMask) then
Result := Integer(E) - Integer(CDoubleBias)
else if E = 0 then
if M = 0 then
// +/-Zero
Result := 0
else
// Denormal
Result := 1 - CDoubleBias
else
// NaN or +/-Infinity
Result := 0;
end;

function GetExponent(const AValue: Extended): Integer; overload;
var
M: UInt64;
E: UInt32;
begin
M := PUInt64(@avalue)^;
E := GetRawExponent(AValue);
if (0 < E) and (E < CExtendedExponentMask) then
Result := Integer(E) - Integer(CExtendedBias)
else if E = 0 then
if M = 0 then
// +/- Zero
Result := 0
else
// Denormal
Result := 1 - CExtendedBias
else
// NaN or +/-Infinity
Result := 0;
end;

C++ Builder

How can I use this with C++ Builder 10? The "Velthuis.BigIntegers.hpp" doesn't exist and I can't generate it, since I only have C++ Builder, but not Delphi installed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.