Simple math operation


#1

I planned to show the math teacher that Sonic Pi can be used to solve mathematical equations but run into a small issue. If you look at the code below the match will never be found when using decimals because of rounding etc. Any suggestions on how to best adapt the code so that the match will be found using decimals?

x=-3
y1=0
y2=0

while (x<3)
  y1=2*x+1
  y2=-x+4

    puts ("Value of x is #{x}, y1 is then #{y1} and y2 is {y2}")
  
  if(y1==y2)
    puts("MATCH when x=#{x} y is then #{y1}")
  end
  
  #This will find a match
  #x=x+1
  
  #This will not find a match
  #x=x+0.1
end

#2

Hey keys,

Welcome to the painful world of floating point math. As you have discovered 0.1 cannot be represented exactly on a computer.. One of the number one rules when programming is you almost never want to compare two floating point numbers for equality. You end up with the errors as shown in your simple program.

However what we can do is check to see if the distance betwen the two numbers is very close.

(a - b ).abs < eps

abs is method on numbers that does the following.

12.abs         #=> 12
(-34.56).abs   #=> 34.56
-34.56.abs     #=> 34.56

and if you choose eps to be a very small number the expression

(a-b).abs < eps

will mean the two numbers are almost equal which is good enough for most purposes. How small eps should be is a hard decision to make but most of the time I would pick

1e-9

which is a shorthand way of writing

0.000000001

which is very very small.

So now your complete program is

x=-3
y1=0
y2=0

while (x<3)
  y1=2*x+1
  y2=-x+4

  #puts ("Value of x is #{x}, y1 is then #{y1} and y2 is {y2}")
  
  if((y1-y2).abs < 1e-9)
    puts("MATCH when x=#{x} y is then #{y1}")
  end
  
  #This will find a match
  #x=x+1
  
  #This will not find a match
  x=x+0.1
end

You can test this out online here where I put your program into an online interpreter and made it run.