F# Generic Math: how to write function with op_GreaterThan

后端 未结 1 704
孤独总比滥情好
孤独总比滥情好 2021-01-28 01:13

in F#, how does one write a generic-math step function?

An (Oliver) Heaviside step function is function that returns zero if x is negative, otherwise it retuns one.

相关标签:
1条回答
  • 2021-01-28 02:04

    Use LanguagePrimitives.GenericZero / GenericOne and let type inference do the rest

    // attempt 1:
    let inline stepFct1 x =
        let zero = LanguagePrimitives.GenericZero 
        if x > zero then x
        else zero
    

    I had a look at the link you sent with the function you want to implement. FSharpPlus (F#+) may help you to write generic math code since it contains a dedicated Generic Numbers module. Or at least you can grab some techniques from there.

    UPDATE

    Regarding your updated question, which takes the complexity to a higher level, here is a solution using the latest version of the F#+ project:

    let inline CDF(x:^T) : ^T = 
        let num x = fromRational (x </ratio/> 1000000000I)
        let (b1,b2,b3)  = (num 319381530I   , num -356563782I  , num 1781477937I)
        let (b4,b5)     = (num -1821255978I , num 1330274429I)
        let (p , c )    = (num  0231641900I , num 0398942280I)
        let (zero, one, two) = 0G, 1G, 2G
        if x > zero then
            let t = one / (one + p * x) 
            (one - c * exp( -x * x / two)* t * (t*(t*(t*(t*b5+b4)+b3)+b2)+b1)) 
        else
            let t = one / (one - p * x) 
            (c * exp( -x * x / two)* t * (t*(t*(t*(t*b5+b4)+b3)+b2)+b1))
    

    Unfortunately at this time I realised some functions were marked as internal in the library and therefore were not exposed, but I re-created them in a working example here so you can test your function, which works nicely with float and float32.

    A new version will be released before end of this year, but in the mean time you can branch it, remove the internals and compile it, or just re-create the functions as I did in the linked example.

    If you are interested in Generic Maths feel free to contribute with code or use cases.

    0 讨论(0)
提交回复
热议问题