Can someone help me with what will the below lines of Java do ? Or can you give an C# equivalent of the below lines of code
public static double[] logSumExp(List<Double> a, List<Double> b) {
double amax = Collections.max(a);
double sum = IntStream.range(0, a.size())
.mapToDouble(i -> Math.exp(a.get(i) - amax) * (i < b.size() ? b.get(i) : 1.0))
.reduce(0.0, Double::sum);
double sign = Math.signum(sum);
sum *= sign;
double abs = Math.log(sum) + amax;
double[] ret = {abs, sign};
return ret;
}
Code using streams in Java usually translates well into LINQ in .NET.
map or mapToXXX works like Select, reduce is Aggregate, but here Sum is more convenient. IntStream.range is Enumerable.Range. Everything else should have a "obvious" equivalent.
public static double[] LogSumExp(IList<double> a, IList<double> b) {
double amax = a.Max();
double sum = Enumerable.Range(0, a.Count)
.Select(i => Math.Exp(a[i] - amax) * (i < b.Count ? b[i] : 1.0))
.Sum();
double sign = Math.Sign(sum);
sum *= sign;
double abs = Math.Log(sum) + amax;
double[] ret = {abs, sign};
return ret;
}
If you are using C# 7+, you should really be returning a tuple instead:
public static (double abs, double sign) LogSumExp(IList<double> a, IList<double> b) {
...
return (abs, sign);
}
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