简体   繁体   中英

Creating an LUT in C# at compile time or run time

I feel like this is a stupid question, but I can't think of a good way to do it.

What I want to do is create a sine wave LUT at compile time or run time. Ideally compile time, but run time is fine if it is much easier to code. However, I want this static object to be accessible by everything that includes its library (I don't want to have to pass it).

I have a feeling that I will be changing the amplitude, the number of samples, the number of cycles (in between compiles, it will be set once the program is running), etc, so I don't want to have to generate the sine wave elsewhere and hard code the values.

I want it to be static because I don't want to have to recreate the sine wave every time I need it. The problem I am having is that I don't have a constructor to initialize it in and I am not sure how else to just make it run one time without passing it to objects or across a few different libraries.

I know this must be possible and probably very easy, but I just not sure where to look. On top of that, it might just be a programming style problem as well so any suggestion would be welcomed.

Thanks

  public static class Sines {
    private static double[] lut;

    static Sines() {
      lut = new double[2048];
      for (int ix = 0; ix < lut.Length; ++ix)
        lut[ix] = Math.Sin(Math.PI * 2 * ix / lut.Length);
    }

    public static double Lookup(int index) {
      return lut[index];
    }
  }

Usage:

double value = Sines.Lookup(1024);

It's not entirely clear what you'll want this wave to do. Are you trying to get the value for any particular time, or is there something you want the wave to do as a whole ?

Is there anything you need to do beyond calling Math.Sin with the right value (based on frequency and time) and then multiply it by the amplitude? Have you already tried that and found it's too slow if you do it every time you need it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM