Proofing a variable and reset within a loop does not working

Hello everybody,

i have the following small loop:

    var = 0.1
    loop do
      sample :bd_pure
      sleep 0.25
      sample :sn_zome, amp: 0.3, attack: var
      sleep 0.25
      if var==0.9
        var = 0.1
      else
        var = var + 0.1
      end
    end

My problem is, that the reset of the attack value doesn’t working. And why is that?
When var got the value of 0.9, the program ignore it and continue with decreasing the value.
What i do wrong?
Thank you for helping.
gastroboss

Hi @gastroboss,

welcome to our forums. It’s lovely to have you here and I hope you stick around for a long time to come :slight_smile:

The issue you’re running into is an age old issue with using floating point values such as 0.1 and relying on them to be accurate.

Try the following:

var = 0.1
10.times do
  puts var
  var = var + 0.1
  sleep 0.125
end

When you run this code, you’ll see strange values like this in the log:

 
{run: 3, time: 1.0}
 └─ 0.8999999999999999

What you’re seeing here is the inaccuracies of floats in action:

0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 = 0.899999999999

Obviously that’s not quite true, but it’s close enough. Although not quite close enough for ==:

0.899999999 == 0.9 #=> false

A simple rule of thumb is to rarely use == with floats unless you’re absolutely sure that accuracy issues like this won’t be an issue. Instead prefer > or <:

    var = 0.1
    loop do
      sample :bd_pure
      sleep 0.25
      sample :sn_zome, amp: 0.3, attack: var
      sleep 0.25
      if var > 0.8
        var = 0.1
      else
        var = var + 0.1
      end
    end

I hope that this helps!

Hi Gastro.

Now Sam’s put you wise to the problem, try messing around
with things!

I got this awesome sound just messing with the samples rate:

var = 0.1
loop do
  sample :sn_zome, rate: 1-var, amp: 0.3, attack: var
  sleep 0.25
  sample :sn_zome, rate: 1+var, amp: 0.3, attack: 0.1
  
  if var > 0.8
    var = 0.1
  else
    var = var + 0.1
  end
end

Eli…

1 Like

Thank you both for your fast, explicit and kindly answer. That solved my problem.
I never expect an answer from the developer of that wonderful program. My complements! This program is an ingenious idea to make music.
Let me personal thank you for that pleasure.
gastro

2 Likes