I have written this function that converts a double to a fraction returning a string:
function getFraction(x: double):string;
var h1, h2, k1, k2, y, a, aux : double;
begin
//Setup the values
h1 := 1;
h2 := 0;
k1 := 0;
k2 := 1;
y := x;
//Generates the fraction
repeat
begin
a := floor(y);
aux := h1;
h1 := a*h1+h2;
h2 := aux;
aux := k1;
k1 := a*k1+k2;
k2 := aux;
y := 1/(y-a) ;
end;
until ( abs(x-h1/k1) > x*0.000001);
//Output
Result := FloatToStr(h1) + '/' + FloatToStr(k1);
end;
And then I call it in this way: Edit7.Text := getFraction(x); where the x is a double. I am using lazarus and I always have this error:
I am sure that the code above has not logic hassles because it becomes from a Java class that I have implemented last week in a project (code).
What am I missing? The full code of my Delphi project can be found here.
The error will surely occur here:
y := 1/(y-a);
When y-a evaluates to 0 then this will result in a divide by zero error. That happens when you pass 0 to the function.
Or perhaps when you evaluate h1/k1 the value of k1 is zero. Again, that's a floating point exception.
Even when you trap those conditions, I cannot make the function return anything that seems remotely sensible to me. So, once you fix the exception condition then you'll have further work.
I'm sure that you could have worked this out in the debugger, even if you could not do so by reading the code. The debugger will tell you which line produced the error and then it is merely a matter of inspecting the value of the operands in the expression.
For what it's worth, your repeat loop is the wrong way around. You're replacing a java do/while with repeat/until - the condition has to invert for this to work.
To avoid divide by zero, just check and break out of the loop. That will save the crash, but I haven't verified that it will always produce the right answer, although it does for previously deadly inputs like 0.25 or 0.5.
repeat
begin
a := floor(y);
aux := h1;
h1 := a * h1 + h2;
h2 := aux;
aux := k1;
k1 := a * k1 + k2;
k2 := aux;
if (y - a = 0) or (k1 = 0) then break; //!!
y := 1 / (y - a) ;
end;
until (Abs(x - h1 / k1) <= x * 0.000001); // Here <= instead of >
Related
I made a program and it constantly tells me that the number I input isn't an integer.
I'm entering 100010110101 and it pops up with this error:
code:
procedure TForm1.Button1Click(Sender: TObject);
var
m,lo,cshl,cdhl,cjhl,csl,cdl,cjl:integer;
begin
m := StrToInt(Edit1.Text);
cshl := m div 100000000000;
cdhl := m div 10000000000 mod 10;
cjhl := m div 10000000000 mod 100;
csl := m div 1000000000 mod 1000;
cdl := m div 100000000 mod 10000;
cjl := m div 10000000 mod 100000;
lo := cjl + cdl * 10 + csl * 100 + cjhl * 1000 + cdhl * 10000 + cshl *100000;
ShowMessage(IntToStr(lo));
end;
Consider how Delphi (and most languages) handle 32-bit integers: Wikipedia
In this context, Integer is a 32-bit integer, and any value less than -2,147,483,648 or greater than 2,147,483,647 IS NOT a valid 32-bit integer.
The "common sense" would indicate, that integers range from -∞ to +∞, but that is not the case in computer architecture.
Use Int64 if you want to "cover" more values.
In your case, the code should look like this:
var
m,lo,cshl,cdhl,cjhl,csl,cdl,cjl:Int64;
begin
m := StrToInt64(Edit1.Text);
...
end;
Cheers
I have a time problem with my program. Given a set of points, it has to say whether all of those points are lying on two different lines.
I wrote code, which has points in array and removes one by one and try calculate it's vector.
But this solution is slow, because it must control all cases of lines. On input with 10,000 points it takes over 10 seconds.
Can someone please tell me if, is here better solution for this problem?
I made this code in Pascal:
uses
math;
type
TPoint = record
x, y: real;
end;
TList = array of TPoint;
function xround(value: real; places: integer): real;
var
muldiv: real;
begin
muldiv := power(10, places);
xround := round(value * muldiv) / muldiv;
end;
function samevec(A, B, C: TPoint): boolean;
var
bx, by: real; // vec A -> B
cx, cy: real; // vec A -> C
lb, lc: real; // len AB, len AC
begin
bx := B.x - A.x;
by := B.y - A.y;
cx := C.x - A.x;
cy := C.y - A.y;
lb := sqrt(bx * bx + by * by);
lc := sqrt(cx * cx + cy * cy);
// normalize
bx := xround(bx / lb, 3);
by := xround(by / lb, 3);
cx := xround(cx / lc, 3);
cy := xround(cy / lc, 3);
samevec := ((bx = cx) and (by = cy)) or ((bx = -cx) and (by = -cy));
end;
function remove(var list: TList; idx: integer): TPoint;
var
i: integer;
begin
remove.x := 0;
remove.y := 0;
if idx < length(list) then
begin
remove := list[idx];
for i := idx to length(list) - 2 do
list[i] := list[i + 1];
setlength(list, length(list) - 1);
end;
end;
var
i, j, lines: integer;
list, work: TList;
A, B: TPoint;
begin
while not eof(input) do
begin
setlength(list, length(list) + 1);
with list[length(list) - 1] do
readln(x, y);
end;
if length(list) < 3 then
begin
writeln('ne');
exit;
end;
lines := 0;
for i := 1 to length(list) - 1 do
begin
work := copy(list, 0, length(list));
lines := 1;
B := remove(work, i);
A := remove(work, 0);
for j := length(work) - 1 downto 0 do
if samevec(A, B, work[j]) then
remove(work, j);
if length(work) = 0 then
break;
lines := 2;
A := remove(work, 0);
B := remove(work, 0);
for j := length(work) - 1 downto 0 do
if samevec(A, B, work[j]) then
remove(work, j);
if length(work) = 0 then
break;
lines := 3; // or more
end;
if lines = 2 then
writeln('YES')
else
writeln('NO');
end.
Thanks, Ferko
APPENDED:
program line;
{$APPTYPE CONSOLE}
uses
math,
sysutils;
type point=record
x,y:longint;
end;
label x;
var
Points,otherPoints:array[0..200001] of point;
n,n2,i,j,k,i1,i2:longint;
function sameLine(A,B,C:point):boolean;
var
ABx,ACx,ABy,ACy,k:longint;
begin
ABx:=B.X-A.X;
ACx:=C.X-A.X;
ABy:=B.Y-A.Y;
ACy:=C.Y-A.Y;
k:=ABx*ACy-ABy*ACx;
if (k=0) then sameLine:=true
else sameLine:=false;
end;
begin
readln(n);
if (n<=4) then begin
writeln('YES');
halt;
end;
for i:=1 to n do readln(Points[i].x,Points[i].y);
for i:=1 to 5 do for j:=i+1 to 5 do for k:=j+1 to 5 do if not (sameLine(Points[i],Points[j],Points[k])) then begin
i1:=i;
i2:=j;
goto x;
end;
writeln('NO');
halt;
x:
n2:=0;
for i:=1 to n do begin
if ((i=i1) or (i=i2)) then continue;
if not sameLine(Points[i1],Points[i2],Points[i]) then begin
inc(n2,1);
otherPoints[n2]:=Points[i];
end;
end;
if (n2<=2) then begin
writeln('YES');
halt;
end;
for i:=3 to n2 do begin
if not sameLine(otherPoints[1],otherPoints[2],otherPoints[i]) then begin
writeln('NO');
halt;
end;
end;
writeln('YES');
end.
Three points A, B and C lie on the same straight line, if vectors AB and AC are collinear or anti-collinear. We can check for collinearity using cross product of vectors - it should be zero.
#LU RD already described this approach is comment, but author probably missed it.
Note that method doesn't suffer from division by zero - there is no division at all.
ABx := B.X - A.X;
ACx := C.X - A.X;
ABy := B.Y - A.Y;
ACy := C.Y - A.Y;
Cross := ABx * ACy - ABy * ACx;
// for integer coordinates
if Cross = 0 then
A,B,C are collinear
If coordinates are float, one must consider some tolerance level. Variants:
//better if available:
if Math.IsZero(Cross)
if Math.SameValue(Cross, 0)
//otherwise
if Abs(Cross) <= SomeEpsilonValue
If coordinate range is very large, numerical error might be significant, so it is worth to normalize tolerance by squared magnitude of coordinate differences:
if Math.IsZero(Cross / Max(ABx * ABx + ABy * ABy, ACx * ACx + ACy * ACy))
I guess the answer to the Q should be devided into two parts.
I. How to know that the given three points belong to the same line?
The answer to this part of the Q was given by #Lurd and then expanded by Mbo.
Let us name their solution function BelongToOneLine(Pnts: array [1..3] of TPoint): boolean; We can consider this part solved.
II. How to decrease time consumption of the algorithm or in other words: how to avoid calling BelongToOneLilne with every possible combination of points as parameters?
Here is the algorithm.
We select 5 distinct points from the task set. 5 is enough (check combination possibilities).
We find the answer to the question if there are at least three points from given five that belong to a single line.
if No - then we do not need to iterate the remaining poins - the answer is that we require more then two lines.
if Yes - (say poins Pt1, Pt2 and Pt3 belong to the same line and Pt4 and Pt5 - don't).
Then we store the points that do not belong to the line Pt1-Pt2-Pt3 from the group-of-five in a distinct array of "outsider" points (or store their indexes in the main array). It may have Length = 0 by the end of this step. This will not affect the rest of the algo.
We get the boolean result of the function BelongToOneLine([Pt1, Pt2, Pt[i]]).
if Yes - we skip the point - it belongs to the line Pt1-Pt2-Pt3.
if No - we store this point in the "outsiders" array.
We watch the length of the OutsidersArray.
if it is <= 2 then the answer to the whole Q is Yes, they do belong to 2 or less lines.
if >2 then we iterate the function BelongToOneLine([OutsiderPt1, OutsiderPt2, OutsiderPt[i]]) until High(OutsiderArray) or until when OutsiderPt[i] does not belong to OutsiderPt1-OutsiderPt2 line. All points of OutsiderArray must belong to the same line otherwise the answer to the whole Q will be negative.
Math note
Without optimization the inerations count will be n! / ((n - k)! * k!).
With the optimization it will be:
5! / ((5-3)! * 3!) + (n - 3) + P(q)outsiders * n that is about 15000 for n = 10000. Most negative count - about 20000.
And another optimization note
Replace declaration of TPoint with integer variables.
Search Results
Featured snippet from the web
For n=1: you need two lines to intersect, so the maximum number of intersections is 0. n=2: Two distinct lines will always intersect in at most one point irrespective of dimensions. ... Explanation: Each set of 2 lines can intersect at one point. Or one point is common intersection for 2 lines.
I have this source code in Delphi, why I get this error "Floating point overflow." when I run the code? and how to correct it?
The error message:
The code:
procedure TForm1.Button1Click(Sender: TObject);
var n, d, i, j, maxiter , iter: Integer;
Lower,Upper : Double;
X, V : TArray<TArray<Double>>;
begin
Lower := 0;
Upper := 0.2;
n := 100;
d := 55;
SetLength(V, n, d);
SetLength(X, n, d);
maxiter := 2000;
iter := 1;
for i:= 0 n-1 do
for j:=0 to d-1 do
begin
X[i][j]:= Lower + (Upper - Lower) * Random;
V[i][j] := 0.1 * X[i][j];
end;
while (iter <= maxiter) do
begin
for i:= 0 to n-1 do
for j:= 0 to D-1 do
V[i][j]:= 5 * V[i][j] + 2.0 * Random;
iter := iter +1;
end;
end;
Look here: V[i][j]:= 5 * V[i][j] + 2.0 * Random;
You make 2000 iterations, so your results might be as large as 7^2000 ~ 10^1690, but max value for Double type is about 10^308. So “Floating point overflow” error is exact diagnosis.
You could see V[] values about 10^307 in debug watch or immediate watch (mouse over V[]) when error occurred.
You can use 10-byte Extended type(probably not available for 64-bit compilers) to avoid overflow for these given variable values, but this is not good solution in general case.
Aside note: You did not set i index value for this code piece:
for j:=0 to d-1 do
begin
X[i][j]:= Lower + (Upper - Lower) * Random;
V[i][j] := 0.1 * X[i][j];
end;
I'm reaching my limit with UInt64 and I was wondering if there are functions which do simple operating options such as +/- , etc. with just strings because they can store just as much RAM as you have... (theoretically)
For example I would like to calculate
24758800785707605497982484480 + 363463464326426 and get the result as a string.
I kinda know how to solve this problems with strings using the number system 0123456789 and kinda do digit by digit and overflow the next position - which would cost a lot more power, but I wouldn't mind this issue...
I would like to have this ability to do such calculations until my RAM just blows up (which would be the real limit...)
Are there such functions which already do that?
Arbitrarily large integers are not supported at the language level in Delphi, but a bit of Googling turns up http://www.delphiforfun.org/programs/Library/big_integers.htm, which can support them as alibrary.
On super computers, its called BCD math (Binary Coded Decimals) and each half-byte of RAM represents a decimal digit [0..9] - not an efficient use of RAM, but huge computations take minimal time (i.e. about 3 mSecs to multiply 2 million digit numbers. A BCD Emulator on a fast PC takes 5 or 6 minutes.
I never need to add big numbers, but I do multiply. Actually I call this routine iteratively to compute for example, 1000000 factorial (a 5,565,709 million digit answer. Str6Product refers to how it chops up a pair of string numbers. s1 and s2 have a practical length limit of about 2^31. The function is limited by what a "string can hold". Whatever that limit is, I've never gotten there.
//==============================================================================
function Str6Product(s1: string; s2: string): string; // 6-13 5:15 PM
var
so,snxt6 : string;
z1,z3, i, j, k : Cardinal; // Cardinal is 32-bit unsigned
x1,x3,xm : Cardinal;
countr : Cardinal;
a1, a2, a3 : array of Int64;
inum, icarry : uInt64; // uInt64 is 64-bit signed
begin
s1 := '00000'+s1;
s2 := '00000'+s2;
z1 := length(s1); // set size of Cardinal arrays
z3 := z1 div 6;
x1 := length(s2); // set size of Cardinal arrays
x3 := x1 div 6;
xm := max(x3,z3);
SetLength(a1,xm+1);
SetLength(a2,xm+1);
// try to keep s1 and s2 about the
// same length for best performance
for i := 1 to xm do begin // from rt 2 lft - fill arrays
// with 4-byte integers
if i <= z3 then a1[i] := StrToInt(copy (s1, z1-i*6+1, 6));
if i <= x3 then a2[i] := StrToInt(copy (s2, x1-i*6+1, 6));
if i > z3 then a1[i] := 0;
if i > x3 then a2[i] := 0;
end;
k := max(xm-x3, xm-z3); // k prevents leading zeroes
SetLength(a3,xm+xm+1);
icarry := 0; countr := 0;
icMax := 0; inMax := 0;
for i := 1 to xm do begin // begin 33 lines of "string mult" engine
inum := 0;
for j := 1 to i do
inum := inum + (a1[i-j+1] * a2[j]);
icarry := icarry + inum;
if icMax < icarry then icMax := icarry;
if inMax < inum then inMax := inum;
inum := icarry mod 1000000;
icarry := icarry div 1000000;
countr := countr + 1;
a3[countr] := inum;
end;
if xm > 1 then begin
for i := xm downto k+1 do begin // k or 2
inum := 0;
for j := 2 to i do
inum := inum + (a1[xm+j-i] * a2[xm-j+2]);
icarry := icarry + inum;
if icMax < icarry then icMax := icarry;
if inMax < inum then inMax := inum;
inum := icarry mod 1000000;
icarry := icarry div 1000000;
countr := countr + 1;
a3[countr] := inum;
end;
end;
if icarry >= 1 then begin
countr := countr + 1;
a3[countr] := icarry;
end;
so := IntToStr(a3[countr]);
for i := countr-1 downto 1 do begin
snxt6 := IntToStr(a3[i]+1000000);
so := so+ snxt6[2]+ snxt6[3]+ snxt6[4]+ snxt6[5]+ snxt6[6]+ snxt6[7];
end;
while so[1] = '0' do // leading zeroes may exist
so := copy(so,2,length(so));
result := so;
end;
//==============================================================================
Test call:
StrText := Str6Product ('742136061320987817587158718975871','623450632948509826743508972875');
I should have added that you should be able to add large numbers using the same methodology - From right to left, fragment the strings into 16 byte chunks then convert those chunks to uInt64 variables. Add the least significant digits first and if it produces a 17th byte, carry that over to the 2nd least significant chunk, add those two PLUS any carry over etc. When otherwise done, convert each 16-byte chunk back to string and concatenate accordingly.
The conversions to and from integer to string and vice-versa is a pain, but necessary for big number arithmetic.
I am trying to get the average color of an image. I tried various methods and now I use the following code, but I could not get the correct result.
Can anyone explain what is wrong with my code?
//load bitmap to curimg
img1.Picture.Bitmap := curimg ; //testing the previous line
//My image is always greater than 25x25 but I only need a 25x25 box
for I := 0 to 25 do
begin
for y := 0 to 25 do
begin
r := r + GetRValue(curimg.Canvas.Pixels[y, I]);
g := g + GetGValue(curimg.Canvas.Pixels[y, I]);
b := b + GetBValue(curimg.Canvas.Pixels[y, I]);
end;
end;
r := r div (25 * 25);
g := g div (25 * 25);
b := b div (25 * 25);
rgbk := RGB(r, g, b);
Result = rgbk;
end;
img1 and image1 of type TImageBox are on my form.
The local variables r,g,b: integer should be initialized to zero first.
One thing which seems wrong with this is that in comments you say that you have 25*25 image, but you loop over 26*26 pixels, so the loops should be:
for I := 0 to 24 do
begin
for y := 0 to 24 do