1

I'm trying to implement this python function in scala. Can someone help?

The Python code is:

from scipy.stats import norm
import numpy as np
def expected_spend(mu,sigma,cl):
    return norm.expect(lambda x: np.minimum(x,cl),lb=0,ub=np.inf,loc=mu,scale=sigma)

I don't have access to many external libraries in scala, I'm trying to implement it using Breeze, but any open source library recommendation is welcome.

  • Not really an answer, but might be useful for those who want to investigate further: [link to class `scipy.stats.norm_gen` source code](https://github.com/scipy/scipy/blob/master/scipy/stats/_continuous_distns.py#L113), [link to `rv_continuous.expect` source](https://github.com/scipy/scipy/blob/master/scipy/stats/_distn_infrastructure.py#L1311). I'm not sure how to port it, maybe Apache Commons Math could be useful. – Andrey Tyukin May 02 '18 at 19:45

1 Answers1

2

I found a more mathematical answer. The

from scipy.stats import norm
import numpy as np
def expected_spend(mu,sigma,cl):
    return norm.expect(lambda x: 
    np.minimum(x,cl),lb=0,ub=np.inf,loc=mu,scale=sigma)

Could be rewritten as two integral of a normal distribution. And the solution for the integral was posted here: https://www.quora.com/How-do-I-evaluate-int_0-infty-frac-min-x-z-exp-frac-x-mu-2-2-sigma-2-sqrt-2-pi-sigma-dx?filter&nsrc=2&snid3=2409997057

So the solution in scala using Breeze is:

 import breeze.math._
 import breeze.numerics._
 import breeze.numerics.constants.Pi
 val min_a_b_gaussian = (mu: Float, sigma: Float, CL: Float) => {
   val CL2 = CL / ( sqrt(2) * sigma )
   val mu2 = mu / ( sqrt(2) * sigma )
   val result = (sigma / sqrt(2) )*((1/sqrt(Pi)) * ( exp(-1*mu2*mu2) - exp(-1*(CL2 - mu2)*(CL2 - mu2)) ) - (CL2 - mu2)*erf(CL2 - mu2) + CL2 + mu2*erf(mu2) )
   result
}