This is the first line of F# that I've tried writing, so apologies because I probably just don't know the right Google keywords to search.
I tried defining a function like so:
let sigmoid x deriv = if deriv then x * (1 - x) else 1 / (1 + System.Math.Exp(-x))
This gives me an error on the System.Math.Exp(-x)
:
The type 'float' does not match the type 'int'
I guess I was expecting the compiler to do type inference on this function and define x
as a float. What am I missing here?
Here is the whole thing that I'm trying to plug in:
let sigmoid x deriv = if deriv then x * (1 - x) else 1 / (1 + System.Math.Exp(-x))
[<EntryPoint>]
let main argv =
sigmoid 1.0 false |> printfn "%A"
0
The compiler infers x
as int
, because you used it in things like 1 - x
. A simple 1
will always be an integer, and you can only use it in arithmetic expressions together with other integers. Your code compiles if you change all your usages of 1
to 1.0
, which will make it a float
and cause x
to be inferred as a float
as well.
This is different from C#, for example, which will coerce the types if necessary and thus allow for mixing integers and floating point numbers in the same expressions. That can lead to an accidental loss of precision under certain circumstances, though, while F# always forces you to state any necessary conversions explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With