I'm trying to make a program that can calculate the calculated fraction of a real number. It works completely fine except when I'm trying to do it for a negative real number, ex "-71/23" or in decimals "-3,086...".
If I calculate the continued fraction of +71/23, I get [3; 11; 2]. This is correct. As far as I've understood, If I then try to do it for -71/23, I should get the same int list, but with the first element being negative (works by pen & paper). So that should be [-3; 11; 2]. But its not working out. I'm getting [-3; -11; -1; -1], which is every number negative plus one extra negative number.
I think that I need to make a branch where I tell the function that only the first number of the int list is allowed to be negative - the rest should be returned positive. I've tried different stuff, but I'm not sure how to work it out.
This is homework by the way.
Thanks in advance, Zebraboard
let rec float2cfrac (x : float) : int list =
let q = int x
let r = x - (float q)
match x with
| _ when r < 0.000000001 && r > -0.000000001 -> [q]
| _ when System.Math.Ceiling(x) - x <0.0001 -> [int (x + 1.0)]
| _ when q < 0 -> [-q] // this is the line where I want to do it, not sure what to do tho
| _ -> q :: float2cfrac (1.0 / r)
printfn "%A" (float2cfrac (-71.0/23.0))
Edit: Moved code with comment and changed format of the code.
Edit: I have now found the solution after lots of work :D simply add an extra line that says that if x is negative then -q instead of q :) Also see the comment below that I have accepted as an answer, you need to change and add some functions :)
| _ when x < 0.0 -> -q :: float2cfrac (1.0 / r)
I would just take the absolute value, then apply the sign at the end:
From fsi: