Post Reply 
Round a decimal value to fraction using Farey series
12-21-2013, 09:04 PM
Post: #4
RE: Round a decimal value to fraction using Farey series
Here is an update.
The program is made for Home but should work in CAS
It list all successives fractions in terminal as they get better
Exemple: FareyMax(π;10000)
Code:
EXPORT FareyMax(Vl, DMax)
// Round a Vl to the best fraction with denominator < DMax
BEGIN
LOCAL VlE, Tmp;
LOCAL DbN,DbD, FnN,FnD, RsN,RsD,RsE;
PRINT();
VlE:= ABS(Vl);
DbN:= IP(VlE); DbD:=1; FnN:=DbN+1; FnD:=1;
RsN:= ROUND(VlE,0); RsD:= 1; RsE:= ABS(VlE-(RsN/RsD));
PRINT(SIGN(Vl)*RsN+"/"+RsD);
WHILE DbD+FnD <= DMax DO
  Tmp:= (DbN+FnN)/(DbD+FnD);
  IF RsE > ABS(VlE-Tmp) THEN RsN:= (DbN+FnN); RsD:= (DbD+FnD); RsE:= ABS(VlE-(RsN/RsD)); PRINT(SIGN(Vl)*RsN+"/"+RsD);END;
  IF Tmp < VlE THEN DbN:= (DbN+FnN); DbD:= (DbD+FnD); ELSE FnN:= (DbN+FnN); FnD:= (DbD+FnD); END;
END;
RETURN "'"+SIGN(Vl)*RsN+"/"+RsD+"'";
// RETURN EXPR("QUOTE("+SIGN(Vl)*RsN+"/"+RsD+")");
END;

Patrice
“Everything should be made as simple as possible, but no simpler.” Albert Einstein
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Round a decimal value to fraction using Farey series - patrice - 12-21-2013 09:04 PM



User(s) browsing this thread: 1 Guest(s)