% From the book % PROLOG PROGRAMMING IN DEPTH % by Michael A. Covington, Donald Nute, and Andre Vellino % (Prentice Hall, 1997). % Copyright 1997 Prentice-Hall, Inc. % For educational use only % File READF64.PL % Routine to read IEEE 64-bit binary numbers from a file :- ensure_loaded('readbyte.pl'). % or use reconsult if necessary % read_f64(-Float) % Reads 8 bytes as an IEEE 64-bit floating--point number. read_f64(Result) :- read_bytes(8,[B0,B1,B2,B3,B4,B5,B6,B7]), Sign is B7 // 128, % 1 bit for sign B7L is B7 mod 128, % first 7 bits of exponent B6H is B6 // 16, % last 4 bits of exponent B6L is B6 mod 16, % first 4 bits of mantissa read_f64_aux(B0,B1,B2,B3,B4,B5,B6L,B6H,B7L,Sign,Result). read_f64_aux(0,0,0,0,0,0,0,0,0,0, 0.0) :- !. read_f64_aux(_,_,_,_,_,_,_,15,127,_, not_a_number) :- !. read_f64_aux(B0,B1,B2,B3,B4,B5,B6L,B6H,B7L,Sign, Result) :- Exponent is B7L*16 + B6H - 1023, Mantissa is ((((((B0/256+B1)/256+B2)/256+B3)/256+B4)/256+B5)/256+B6L)/16 + 1, power(-1,Sign,S), power(2,Exponent,E), Result is S * Mantissa * E. % power(X,N,Result) % Finds the Nth power of X (for integer N). % Needed because some Prologs still don't have % exponentiation in the 'is' predicate. power(_,0,1) :- !. power(X,E,Result) :- E > 0, !, EE is E-1, power(X,EE,R), Result is R*X. power(X,E,Result) :- % E < 0, EE is E+1, power(X,EE,R), Result is R/X.