haskell - What is the nicest way to make a function that takes Float or Double as input? -
say want implement fermi function (the simplest example of logistic curve) if it's passed float
returns float
, if it's passed double
returns double
. here's i've got:
e = 2.7182845904523536 fermifunc :: (floating a) => -> fermifunc x = let 1 = fromintegral 1 in one/(one + e^(-x))
the problem ghc says e
double
. defining variable one
kinda gross. other solution i've thought of define function doubles:
e = 2.7182845904523536 fermifuncdouble :: double -> double fermifuncdouble x = 1.0/(1.0 + e^(-x))
then using either
:
fermifunc :: (floating a) => either float double -> fermifunc right x = double2float (fermifuncdouble (float2double x)) fermifunc left x = fermifuncdouble x
this isn't exciting though because might have written separate function float
case handles casting , calls fermifuncdouble
. there nice way write function both types?
don't write e^x
, ever, in language. not exponential function, it's power function.
the exponential function called exp
, , definition has little power operation โ it's defined, depending on taste, taylor series or the unique solution ordinary differential equation dโd๐ฅ exp ๐ฅ = exp ๐ฅ boundary condition exp 0 = 1. now, happens that, rational n, have exp n โก (exp 1)n , motivates defining power operation numbers in โ or โ addition โ, namely as
az := exp (z ยท ln a)
...but e๐ฅ should understood shortcut writing exp(๐ฅ) itself.
so rather defining e
somewhere , trying take power of it, should use exp
is.
fermifunc :: floating => -> fermifunc x = 1/(1 + exp (-x))
...or indeed
fermifunc = recip . succ . exp . negate
Comments
Post a Comment