Does F# have a built in cube root function? I know I can use exponentiation to compute cuberoots but it won't type check in my case since I want to take the cuberoot of a quantity of type float and get a float.
1 Answers
I don't think there is a built-in function to calculate the cube root with units of measure (I assume it would be in the primitive operators module where sqrt
and others are), so I think the only option is to use exponentiation.
However, you can use exponentiation without units and wrap the unit-unsafe operation in a function that adds units, so you get function with correct units:
let cuberoot (f:float<'m^3>) : float<'m> =
System.Math.Pow(float f, 1.0/3.0) |> LanguagePrimitives.FloatWithMeasure
Note that F# does not support fractional units so you can write cuberoot (10.0<m^3>)
or cuberoot (10.0<m^9>)
, but if you write cuberoot (10.0<m>)
then it will not type-check, because the result would be meters to 1/3
(and that's a fractional unit).
This sample is only implementing cuberoot
for float
. If you wanted to write overloaded function that works with other numeric types (I guess you might need float32
) then it gets a bit uglier (so I would not recommend that unless necessary), but you can use a trick with intermediate type with multiple overloads like, for example, in this answer.

- 1
- 1

- 240,744
- 19
- 378
- 553
-
Thanks for the answer. It's a bit disappointing but I can live with this solution. – jz87 Jan 15 '13 at 23:17
-
2IMO using LanguagePrimitives.FloatWithMeasure instead of unbox will be more descriptive (and -1 boxing operation) – desco Jan 16 '13 at 03:10
-
@desco Good point, thanks! Using `FloatWithMeasure` is definitely a better choice. I updated the answer. – Tomas Petricek Jan 16 '13 at 09:49