The Computer Language
24.04 Benchmarks Game

spectral-norm C# .NET program

source code

/* The Computer Language Benchmarks Game
   https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
   
   contributed by Isaac Gouy 
*/

using System;

class SpectralNorm
{
   public static void Main(String[] args) {        
      int n = 100;
      if (args.Length > 0) n = Int32.Parse(args[0]);

      Console.WriteLine("{0:f9}", new SpectralNorm().Approximate(n));
   }

   double Approximate(int n) {
      // create unit vector
      double[] u = new double[n];       
      for (int i=0; i<n; i++) u[i] =  1;

      // 20 steps of the power method
      double[] v = new double[n];  
      for (int i=0; i<n; i++) v[i] = 0;

      for (int i=0; i<10; i++) {
         MultiplyAtAv(n,u,v);
         MultiplyAtAv(n,v,u);
      }

      // B=AtA         A multiplied by A transposed
      // v.Bv /(v.v)   eigenvalue of v 
      double vBv = 0, vv = 0;
      for (int i=0; i<n; i++) {
         vBv += u[i]*v[i];
         vv  += v[i]*v[i];
      }

      return Math.Sqrt(vBv/vv);
   }


   /* return element i,j of infinite matrix A */
   double A(int i, int j){
      return 1.0/((i+j)*(i+j+1)/2 +i+1); 
   }

   /* multiply vector v by matrix A */
   void MultiplyAv(int n, double[] v, double[] Av){
      for (int i=0; i<n; i++){
         Av[i] = 0;
         for (int j=0; j<n; j++) Av[i] += A(i,j)*v[j];
      }
   }

   /* multiply vector v by matrix A transposed */
   void MultiplyAtv(int n, double[] v, double[] Atv){
      for (int i=0;i<n;i++){
         Atv[i] = 0;
         for (int j=0; j<n; j++) Atv[i] += A(j,i)*v[j];
      }
   }

   /* multiply vector v by matrix A and then by matrix A transposed */
   void MultiplyAtAv(int n, double[] v, double[] AtAv){
      double[] u = new double[n];
      MultiplyAv(n,v,u);
      MultiplyAtv(n,u,AtAv);
   }
}
    

notes, command-line, and program output

NOTES:
64-bit Ubuntu quad core
.NET SDK 8.0.204
Host Version: 8.0.4
Commit: 2d7eea2529
<AllowUnsafeBlocks>true
<ServerGarbageCollection>true
<ConcurrentGarbageCollection>true
<PublishAot>false
<OptimizationPreference>Speed
<IlcInstructionSet>native


 Fri, 26 Apr 2024 01:19:31 GMT

MAKE:
cp spectralnorm.csharpcore Program.cs
cp Include/csharpcore/program.csproj .
mkdir obj
cp Include/csharpcore/project.assets.json ./obj
/usr/bin/dotnet build -c Release --use-current-runtime  	
MSBuild version 17.9.8+b34f75857 for .NET
  Determining projects to restore...
  Restored /home/dunham/all-benchmarksgame/benchmarksgame_i53330/spectralnorm/tmp/program.csproj (in 180 ms).
  program -> /home/dunham/all-benchmarksgame/benchmarksgame_i53330/spectralnorm/tmp/bin/Release/net8.0/linux-x64/program.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:03.97

5.79s to complete and log all make actions

COMMAND LINE:
 ./bin/Release/net8.0/linux-x64/program 5500

PROGRAM OUTPUT:
1.274224153