Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Object-Pascal / Delphi-Language (https://www.delphipraxis.net/32-object-pascal-delphi-language/)
-   -   Delphi Small piece from JavaScript to Delphi won't work (https://www.delphipraxis.net/197079-small-piece-javascript-delphi-wont-work.html)

WojTec 16. Jul 2018 19:31

Delphi-Version: 10.2 Tokyo

Small piece from JavaScript to Delphi won't work
 
This is original code to convert float to fraction:

Code:
function float2rat(x) {
    var tolerance = 1.0E-6;
    var h1=1; var h2=0;
    var k1=0; var k2=1;
    var b = x;
    do {
        var a = Math.floor(b);
        var aux = h1; h1 = a*h1+h2; h2 = aux;
        aux = k1; k1 = a*k1+k2; k2 = aux;
        b = 1/(b-a);
    } while (Math.abs(x-h1/k1) > x*tolerance);
   
    return h1+"/"+k1;
}
Delphi-Quellcode:
uses Math;

function float2rat(x: Extended): string;
const
  tolerance = 1.0E-6;
var
  h1, h2, k1, k2, a, aux: Int64;
  b: Extended;
begin
  h1:=1;
  h2:=0;
  k1:=0;
  k2:=1;
  b := x;
  repeat
  begin
    a := Floor(b);
    aux := h1;
    h1 := a*h1+h2;
    h2 := aux;
    aux := k1;
    k1 := a*k1+k2;
    k2 := aux;
    b := 1/(b-a);
  end until (Abs(x - h1 / k1) > x * tolerance);

  Result := Format('%d / %d', [h1, k1]) ;
end;
Code:
// JS: float2rat(9.5) = 19/2
// D: float2rat(9.5) = 9/1
What's wrong with my port?

gammatester 16. Jul 2018 20:18

AW: Small piece from JavaScript to Delphi won't work
 
Your translation of do {..} while is wrong. Your stopping criterion should be as given below
Delphi-Quellcode:
 repeat
    a := Floor(b);
    aux := h1;
    h1 := a*h1+h2;
    h2 := aux;
    aux := k1;
    k1 := a*k1+k2;
    k2 := aux;
    if a=b then break;
    b := 1/(b-a);
  until (Abs(x - h1 / k1) <= x * tolerance);
Note the safe-guard against division by zero. Don't know why JS can divide by zero - or is it quietly ignored?

With these changes you get 9.5 = 19/2.

WojTec 16. Jul 2018 20:49

Re: Small piece from JavaScript to Delphi won't work
 
Nice, is working, thank you!

And how about types, are they correct?

gammatester 16. Jul 2018 21:31

AW: Re: Small piece from JavaScript to Delphi won't work
 
Zitat:

Zitat von WojTec (Beitrag 1407452)
Nice, is working, thank you!
And how about types, are they correct?

They should work for x in the Longint range. You should check also if frac(x) is zero and output int(x) and 1. The code crashes e.g. for x=1.0+MaxLongint because k1 will become zero and h1/k1 throws a divide-by-zero exception.


Alle Zeitangaben in WEZ +1. Es ist jetzt 00:20 Uhr.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz