Decimals to Fractions
Is there any way to convert decimals to fractions in C++? Some sort of function? For example, how can I get the computer to know that 2.5 = 5/2 ?
I'm trying to write a program that will convert slope-intercept form (y=mx+b) to the general form (Ax+By=C). Going from the General Form to Slope-Intercept is a piece of cake (m = -A/B, b = C/B) but without knowing how to convert decimals to fractions, I can't figure out how to go from Slope-Intercept to General.
Thanks in advance!
Put simply, no. (The long answer is write or find your own numeric class)
Why can't you just keep everything as floating point numbers?
I can't keep floating point decimals because I'm trying to convert the Slope-Intercept Form of a line to General Form. Slope-Intercept is:
y = mx + b
and General Form is:
Ax + By = C
You can go from General to Slope-Intercept pretty easily because
m = -(A/B) and b = C/B
But in order to go from Slope-Intercept to General, you need to figure out what the numerator (A and C) and the denominator (B) are. If I know that the value of b is 2.5, I need to have a way for the computer to know that the numerator would be 5 and the denominator would be 2.
make ur own by using two loops. When the values created by the loop create a fraction that is too great, you can have it leave the loop and start again on the first loop. If you want to restrict the size the loop goes to, you can use for loops. Good luck and sorry if the explanation isnt clear, it is early in the morning here.
You have the equation
y = mx + b
and m and b are known. A method to calculate A, B and C is to calculate 3 points on the line, say (x1,y1), (x2,y2) and (x3,y3). Then you have a set of three equations and three variables which can be solved.
A x1 + B y1 = C
A x2 + B y2 = C
A x3 + B y3 = C
This is quite easy. With some linear algebra or just isolating the variables you could calculate this.
Note that converting from decimal to fraction is not always possible. For example: pi. Though there is an algorithm which you can use to approximate decimals by fractions. In case of 2.5 it will be exact instead of an approximation.
* Constants *
N = number of iterations
PI = just pi, the decimal to be approximated
* Initialisation *
x  = PI
p [-1] = 0
p  = 1
q [-1] = 1
q  = 0
* The algorithm *
for n = 1 to N do
d [n] = int (x [n])
p [n] = d [n] * p [n - 1] + p [n - 2]
q [n] = d [n] * q [n - 1] + q [n - 2]
x [n + 1] = 1 / (x [n] - d [n])
n = n + 1
x' = p [N] / q [N]
I have a lecture from university which explains the algorithm, but it's in Dutch. If you like to, I'll translate the explanation to English.