## exact calc whit fractor's [ breuken ]

General FreeBASIC programming questions.
bluatigro
Posts: 618
Joined: Apr 25, 2012 10:35
Location: netherlands

### exact calc whit fractor's [ breuken ]

this is a way to calculate exact whit fractor's [ breuken ]
whit doubles you wil get rounding error's

Code: Select all

`'' bluatigro 2 nov 2018'' fractor libfunction gcd( a as long , b as long ) as long  while a <> b    if a < b then      b = b - a    end if    if a > b then      a = a - b    end if  wend  return aend functiontype fractor  dim as long a , b  declare constructor ()  declare constructor ( i as long , j as long )  declare function tostr() as stringend type constructor fractor()end constructorconstructor fractor( i as long , j as long )  a = i  b = jend constructor function fractor.tostr() as string  return str( a ) + " / " + str( b )end functionoperator + ( f1 as fractor , f2 as fractor ) as fractor  dim as long a = f1.a * f2.b + f2.a * f1.b  dim as long b = f1.b * f2.b  dim as long c = gcd( a , b )  return type( a / c , b / c )end operatoroperator - ( f1 as fractor , f2 as fractor ) as fractor  dim as long a = f1.a * f2.b - f2.a * f1.b  dim as long b = f1.b * f2.b  dim as long c = gcd( a , b )  return type( a / c , b / c )end operatoroperator / ( f1 as fractor , f2 as fractor ) as fractor  dim as long a = f1.a * f2.b  dim as long b = f1.b * f2.a  dim as long c = gcd( a , b )  return type( a / c , b / c )end operatoroperator * ( f1 as fractor , f2 as fractor ) as fractor  dim as long a = f1.a * f2.a   dim as long b = f1.b * f2.b  dim as long c = gcd( a , b )  return type( a / c , b / c )end operatordim as fractor f1 , f2 , f3f1 = fractor( 1 , 4 )f2 = fractor( 1 , 6 )f3 = f1 + f2print "a =     " + f1.tostr()print "b =     " + f2.tostr()print "a + b = " + f3.tostr()f3 = f1 - f2print "a - b = " + f3.tostr()f3 = f1 * f2print "a * b = " + f3.tostr()f3 = f1 / f2print "a / b = " + f3.tostr()print "[ game over : push return ]"sleep `
counting_pine
Posts: 6176
Joined: Jul 05, 2005 17:32
Location: Manchester, Lancs

### Re: exact calc whit fractor's [ breuken ]

Hi. Is a fractor another name for a fraction?
I don't know if you're looking for help with the code, but the gcd() function may have problems with non-positive numbers, or where one number is much larger than the other (e.g. print 'gcd(2e9, 1)').
You can speed up the latter cases by using Mod, and the negative cases by using Abs(), and for zero, you should just return the other number, i.e. gcd(a, 0) = a (https://proofwiki.org/wiki/GCD_with_Zero).
bluatigro
Posts: 618
Joined: Apr 25, 2012 10:35
Location: netherlands

### Re: exact calc whit fractor's [ breuken ]

if a fraction = i / j then yes
the way whit mod i do not know
if it is faster give gcd() whit mod

there are more costructs in math
that in code you use a double
[ example : square root ]
can somthing like this done whit dose ?