Hello,
I am currently trying to make a program that uses fractions, such as 1/4, and adds them and subtracts them( i know it sounds stupid, ut i have a special use for it). I dont know how to make fractions, and doubt you can, so i use their decimal equivalents. Anyway, whenever i try to use any type of variable, includng floating point variables, i always get 0 or 1, never .25 or . anything when i didve the two numbers ( like 4 and 1). LIkewise, when i do 10/3, i get 3.0, and never get a decimal. Is there a way to fix this and extend the number of zeros there are after the decimal, or should i learn another programming language for this?
Thanks
To get a float result, then at least one of the values in the expression needs to be a float also.
You should also be aware that floats are only single precision in Blitz and therefore not very accurate. So don't rely on 10.0/4 being 0.25. Because it's more likely to be 0.2499999 or something.
Are there any programming languages where the single precisions are extremely accurate?
Why not just keep your fractions AS fractions? In other words, maybe create a 'fraction' type to store your values.
something like this:
Type Fraction
Field Numerator
Field Denominator
End Type
Sample code:
Type Fraction
Field N ;Numerator
Field D ;Denominator
End Type
a.Fraction = New Fraction
b.Fraction = New Fraction
c.Fraction = New Fraction
a\N = 1: a\D = 4 ;1/4
b\N = 10: b\D = 3 ;10/3
c = Add(a, b)
Print "1/4 + 10/3 = " + c\N + "/" + c\D
a\N = 1: a\D = 11 ;1/11
b\N = 120: b\D = 11 ;120/11
c = Add(a, b)
Print "1/11 + 120/11 = " + c\N + "/" + c\D
WaitKey
Delete Each Fraction
End
Function Add.Fraction(num1.Fraction, num2.Fraction)
If sum.Fraction = Null Then sum.Fraction = New fraction
sum\N = num1\N * num2\D + num2\N * num1\D
sum\D = num1\D * num2\D
sum = Simplify(sum)
Return sum
End Function
Function Simplify.Fraction(num.Fraction)
Repeat
foundDivisor = False
For attempt = 1 To 5
Select attempt
Case 1
divisor = 2
Case 2
divisor = 3
Case 3
divisor = 5
Case 4
divisor = 7
Case 5
divisor = 11
;Case 6
;continue on for as many prime numbers as you want...
End Select
If num\N Mod divisor = 0 And num\D Mod divisor = 0
num\N = num\N / divisor
num\D = num\D / divisor
foundDivisor = True
Exit
EndIf
Next
Until foundDivisor = False
Return num
End Function
You owe me ;) ...
You know, when I was in sixth grade and was learing how to handle fractions, I thought, OH GOD, this really sucks!
But when I later got into algebra and trigonometry, I realized that using fractions was SO MUCH BETTER than dealing with inaccurate decimals. For instance, a number like 1/3 is perfectly represented as a fraction, but can never be perfectly represented as a decimal. That is when I truly realized how valuable fractions were.
Hey Paul, was the code I submitted of any help to you?