views:

180

answers:

2

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

A: 

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?

Jon Skeet
I should admit that this is mainly academic as I could probably get away with doing the Math.Sin every time I need a value. However, coming from an embedded and FPGA programming background, efficiency was the first thing that popped into my head and, even if I could just do Math.Sin, it would be nice to know how to do this.But I will be using it for a number of things, the main one (which concerned me about time) a correlation filter on waves that have 8192 samples.
EatATaco
@EatATaco: I would suggest you first design what your "Wave" class should look like in terms of API - and then you may find it's very easy to implement the caching internally. (I'd suggest building an array.)
Jon Skeet
+1  A: 
  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);
Hans Passant
Thanks, exactly what I was looking for.
EatATaco