I am orienting in ruby and crystal. Because the syntax is so similar:
def interpolation(x,y,z)
(z - x) / (y - x)
end
puts interpolation(1,3,2)
end code
I read that the last statement in a method is returned. Why is this method returning 0? it should return 0.5
ps. how to correctly post code into this forum?
             
            
              
              
              
            
            
                
                
              
           
          
            
              
                pcl
                
              
              
              
                  
                  
              2
              
             
            
              When you use integers, you get integer division. You can use to_f to force a number to be a float:
> 4/3
 => 1 
> 4.0/3
 => 1.3333333333333333 
> 4.to_f/3
 => 1.3333333333333333 
> def interpolation(x,y,z)
>   (z - x) / (y - x)
> end
 => :interpolation 
> interpolation(1,3,2)
 => 0 
> interpolation(1.0,3,2)
 => 0.5 
> def interpolation(x,y,z)
>   (z-x).to_f/(y-x).to_f
> end
 => :interpolation 
> interpolation(1,3,2)
 => 0.5 
Three back ticks top-and-bottom.
             
            
              
              
              2 Likes
            
            
                
                
              
           
          
            
            
              Ah now I understand! I ended up with this for the eye-candy:
def interpolation(x,y,z)
  x = x.to_f
  y = y.to_f
  z = z.to_f
  (z - x) / (y - x)
end
             
            
              
              
              1 Like