Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java IntStream, Range and mapToDouble and reduce function equivalent in C#

Tags:

java

c#

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;
  }
like image 923
Nikhil Avatar asked Oct 17 '25 16:10

Nikhil


1 Answers

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);
}
like image 52
Sweeper Avatar answered Oct 20 '25 06:10

Sweeper