title: Ruby poor performance on algorithm to calculate moving average (compared to java)
body: <p>I made this algorithm to find when the Standard deviation became smaller than the average for a set of values, by increasing the order of a moving average.
  Typically my data has about 300 values, mostly zeros, and the order of the moving average that meets the criteria is about 50.</p>
  
  <p>The problem is that i already have this same algorithm in java and it runs in a few seconds (less than 5), and in ruby it takes about 3 to 5 minutes.</p>
  
  <p>As I'm new to ruby on rails, I may be doing some foolish that compromise the performance.</p>
  
  <p>So, is there anyway to improve this in ruby on rails? If not, how come java calculate this 100x faster? Since i'm using ruby on rails with postgresql, should i build this function on PL/pgSQL?</p>
  
  <p>Here's the algorithm:  </p>
  
  <pre><code>while mvg_avg&lt;mvg_st_dev do
        freq_on+=1 #fre_on = the order of the moving average
        values = Array.new(date_value.count-freq_on+1, Float(0)) #date_value is the original array with the values. 
        sum_values = 0 #sum_values will be used to calculate the average
  
        #here i will build the new array, with the moving average values, and then i calculate the new total average for this new array.
        for i in 0..(date_value.count-1-freq_on+1)
          for j in i..(i+freq_on-1) #go through the date(i) until date(i+order-1) 
            values[i]+= date_value[j]
          end
          values[i]=values[i]/freq_on
          sum_values+=values[i]
        end
  
        mvg_avg = sum_values / values.size.to_f
  
        #now i find out the standard deviation
        sumSt=0
        values.each do |value|
          sumSt+=(value-mvg_avg)**2
        end
        mvg_st_dev=Math.sqrt(sumSt/date_value.count)
  
      end
  </code></pre>
  
  <p><strong>UPDATE 2018-02-07 #1</strong>
  Keyword that was causing all this trouble: Casting.</p>
  
  <p>My array with the data were mostly Integer values, and inside the loops they were been used as float. Once that I built my data as Float before entering the loops, the code run only about 10x slower than Java (witch is acceptable, as Tadman commented that ruby math runs about this slower than Java).</p>
  
  <p>Here is where i'm build my data:</p>
  
  <pre><code>  def self.pushProductValuesToArray(dates, hashDps)
      date_value = Array.new
      dates.each do |date|
        dp = hashDps[date]
        date_value.push (dp.nil? ? 0.0 : dp.value.to_f) #here i was pushing integers to the array, instead of float.
      end
      return date_value
    end
  </code></pre>