0

Does anyone know how I could generate a random number in a range in iOS? I am currently working on a synthesizer in iOS (using SpriteKit and AudioKit) and I am trying to modify the loudness of the synth with changing its variability whenever a slider is being moved as well.

This is what my code looks like:

[Synth setAmplitude: 0.5 + (slider.currentValue * loudnessVar)];

where 0.5 is the default amplitude value and loudnessVar is a random number.

Since, the slider returns values from -170 to 170 , I would need a relatively low number in order to set a value between 0 and 1.

Is anyone able to help with this?

  • 2
    What have you tried so far to generate a random number? Did you have a look at this [question](http://stackoverflow.com/questions/160890/generating-random-numbers-in-objective-c) discussing the approaches on generating random numbers in Objective-C? I think this could lead you in the right direction. – Mike F Mar 03 '16 at 11:49

1 Answers1

3

The way to generate a random number in a range is:

NSInteger random = min + arc4random() % (max - min);

So, you can generate a number between 1-20 and divide it by 1000, it's just an example.

I.

isanjosgon
  • 1,829
  • 1
  • 13
  • 12