Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Fraction/Decimal conversions
Message
From
28/12/1998 10:26:23
 
 
To
26/12/1998 16:00:13
General information
Forum:
Visual FoxPro
Category:
Coding, syntax & commands
Miscellaneous
Thread ID:
00170505
Message ID:
00170766
Views:
14
>Anybody got any code to convert values back and forth between fractions and decimals?

Let´s suppose you represent decimals as pairs of numbers (NUM, DEN). (I'm using words like "decimals" or "numbers" loosely here. It would be better to talk about "real numbers", "integers", "naturals", and so on.)

To convert a fraction to a decimal, just divide NUM/DEN.

To convert a decimal to a fraction, use something like this:
CLEAR
nORIG = PI() 
nORIG = SQRT(10)

*												
*	Finds a rational (nNUM/nDEN) approximation	
*	to any real number nORIG.					
*												

#DEFINE ZEROES 0.0000000000000000000000000000000

*											
*	Let´s start with an easy approximation.	
*											
nNUM = ROUND(nORIG,0) + ZEROES
nDEN = 1 + ZEROES
N = nORIG - nNUM

DO WHILE .T.
	*											
	*	Print values, and check whether our		
	*	approximation is good enough.			
	*											
	N = nORIG - nNUM/nDEN
	? STR(nNUM,20), STR(nDEN,20), STR(nNUM/nDEN,20,18), STR(nORIG,20,18), STR(N,20,18)
	IF	ABS(N)<1E-20
		EXIT
	ENDIF

	*											
	*	Let's better our approximation. 1/INVN 	
	*	approximates the difference between the	
	*	original number and nNUM/nDEN, so let´s	
	*	add both fractions together.			
	*											
	INVN = ROUND(1/N,0)
	nNUM = nNUM*INVN + nDEN
	nDEN = nDEN*INVN

	*											
	*	Euclid's algorithm; let's scale down	
	*	nNUM, nDEN, so they are mutually prime	
	*											
	A=nNUM
	B=nDEN
	DO WHILE B<>0
		C = MOD(A,B)
		A = B
		B = C
	ENDDO
	nNUM = nNUM/A
	nDEN = nDEN/A
ENDDO
HTH!
Previous
Reply
Map
View

Click here to load this message in the networking platform