# Trouble migrating formula from JavaScript to Ruby

**URL:** <https://www.ruby-forum.com/t/trouble-migrating-formula-from-javascript-to-ruby/58952>\
**Category:** Ruby\
**Created:** [April 27, 2006, 12:07pm UTC](https://www.ruby-forum.com/t/trouble-migrating-formula-from-javascript-to-ruby/58952 "2006-04-27T12:07:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ingoweiss](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/77aa72/32.png) [@ingoweiss](https://www.ruby-forum.com/u/ingoweiss)\
**Post date:** [April 27, 2006, 12:07pm UTC](https://www.ruby-forum.com/t/trouble-migrating-formula-from-javascript-to-ruby/58952/1 "2006-04-27T12:07:31Z")

</div>

Hi,

I am trying (unsuccessfully) to migrate a formula (for calculating  
distances between lat/lng positions) from JavaScript to Ruby:

//JavaScript:  
dlng = p2\_lng - p1\_lng  
dlat = p2\_lat - p1\_lat  
a = (sin(dlat/2))^2 + cos(p1\_lat) \* cos(p2\_lat) \* (sin(dlon/2))^2  
c = 2 \* atan2( sqrt(a), sqrt(1-a) )  
distance = R \* c (where R is the radius of the Earth)

#Ruby:  
dlng = p2\_lng - p1\_lng  
dlat = p2\_lat - p1\_lat  
a = (Math.sin(dlat/2))\*\*2 + Math.cos(p1\_lat) \* Math.cos(p2\_lat) \*  
(Math.sin(dlng/2))\*\*2  
c = 2 \* Math.atan2( Math.sqrt(a), Math.sqrt(1-a) )  
distance = 6373 \* c #(radius of the Earth: 6373km

Any idea why the Ruby one returns incorrect numbers?

Ingo W.

---

<div class="post-metadata">

**Author:** ![ingoweiss](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/77aa72/32.png) [@ingoweiss](https://www.ruby-forum.com/u/ingoweiss)\
**Post date:** [April 27, 2006, 12:23pm UTC](https://www.ruby-forum.com/t/trouble-migrating-formula-from-javascript-to-ruby/58952/2 "2006-04-27T12:23:46Z")

</div>

is it possible that you need to make numbers explicitly float? eg: 2 --\>  
2.0
