![]() |
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:
What's wrong with my port?
// JS: float2rat(9.5) = 19/2
// D: float2rat(9.5) = 9/1 |
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:
Note the safe-guard against division by zero. Don't know why JS can divide by zero - or is it quietly ignored?
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); With these changes you get 9.5 = 19/2. |
Re: Small piece from JavaScript to Delphi won't work
Nice, is working, thank you!
And how about types, are they correct? |
AW: Re: Small piece from JavaScript to Delphi won't work
Zitat:
|
Alle Zeitangaben in WEZ +1. Es ist jetzt 20:02 Uhr. |
Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz