Having difficulty transferring mathematical algorithms from JavaScript to Java

Having difficulty translating JavaScript code that converts between Latitude/Longitude & OS National Grid Reference points to Java. ()

Encountering variations in the results of certain mathematical operations. The javascript and java code snippets provided below show a discrepancy in the Ma calculation output, with 0.04195508514183418 being the result in javascript, while 0.04195511450680837 is produced in Java. Despite confirming identical input values for the calculation.

This represents the JavaScript code:

OsGridRef.osGridToLatLong = function(gridref) {
    var E = gridref.easting;
    var N = gridref.northing;

    var a = 6377563.396, b = 6356256.910;              
    var F0 = 0.9996012717;                             
    var lat0 = 49*Math.PI/180, lon0 = -2*Math.PI/180;  
    var N0 = -100000, E0 = 400000;                     
    var e2 = 1 - (b*b)/(a*a);                          
    var n = (a-b)/(a+b), n2 = n*n, n3 = n*n*n;

    var lat=lat0, M=0;
    var count = 0;

    do {

       count++;
       lat = (N-N0-M)/(a*F0) + lat;

       console.log("pre ma calc");
                console.log("n = " + n);
                console.log("n2 = " + n2);
                console.log("n3 = " + n3);
                console.log("lat = " + lat);
                console.log("lat0 = " + lat0);

       var Ma = (1 + n + (5/4)*n2 + (5/4)*n3) * (lat-lat0);

        console.log("post ma calc ma = " + Ma);

Utilizing the following Javascript code produces this output:

pre ma calc test.html:68
n = 0.0016732202503250534 
n2 = 0.0000027996660060978346 
n3 = 4.684457855549562e-9 
lat = 0.8970962185213205 
lat0 = 0.8552113334772214 
post ma calc ma = 0.04195511450680837 

The corresponding java code snippet looks like this:

LatLon osGridToLatLong(OsGridRef osGridRef) {

    int E = osGridRef.easting;
          int N = osGridRef.northing;


          double a = 6377563.396, b = 6356256.910;             
          double F0 = 0.9996012717;                           
          double lat0 = 49*Math.PI/180, lon0 = -2*Math.PI/180;  
          double N0 = -100000, E0 = 400000;                   
          double e2 = 1 - (b*b)/(a*a);                         
          double n =(a-b)/(a+b), n2 = n*n, n3 = n*n*n;

         ...
     } while (N-N0-M >= 0.00001);  

Executing this Java code provides the subsequent output:

07-03 12:36:03.413: E/DSDS(779): pre ma calc
07-03 12:36:03.423: E/DSDS(779): n = 0.0016732202503250534
07-03 12:36:03.423: E/DSDS(779): n2 = 2.7996660060978346E-6
07-03 12:36:03.443: E/DSDS(779): n3 = 4.684457855549562E-9
07-03 12:36:03.473: E/DSDS(779): lat = 0.8970962185213205
07-03 12:36:03.473: E/DSDS(779): lat0 = 0.8552113334772214
07-03 12:36:03.473: E/DSDS(779): post ma calc ma = 0.04195508514183418

Answer №1

When 5 is divided by 4, the result will be an integer division which yields <code>5 / 4 = 1.25 = 1

To ensure precision in calculations involving Ma, Mb, Mc, and Md, it is recommended to change the operation to 5.0 / 4 so floating point types are used instead of integers.

This adjustment may not only make your results consistent but also accurate according to mathematical rules. It appears that the code migration was done correctly otherwise.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending an integer array to an MVC Controller

I am attempting to send an array of integers from JavaScript to an MVC controller that requires 2 parameters - an integer array and an integer value. This is needed for a Page Redirect to the View returned by the Controller Action. var dataArray = getAllI ...

Enhance your HTML coding experience in Notepad++ with EJS syntax highlighting feature

While using Notepad++, I encountered some frustrating issues with syntax highlighting in HTML files containing JavaScript and EJS (embedded Java Script) parts. The highlighting was often messy, as seen here: https://i.sstatic.net/n2Dm5.png EJS allows for ...

Eliminating the 'white-space' surrounding concealed images

I am currently working on a project where I have a list of images that need to be hidden or shown based on the click event of specific <li> elements. While I have managed to achieve this functionality successfully, I am facing an issue with white spa ...

Deactivating the Grid and its offspring in React.js MUI

Is it possible to Disable the Grid (MUI Component) and its Children in React js? Additionally, how can we Disable any Container and its items in React js, regardless of the type of children they have? For example: <Grid item disabled // ...

Discovering objects generated by Hibernate: Techniques for identification

In our current project, we are utilizing hibernate3 and spring 3. We have a large number of domain objects with some eager relations between them. I am working on optimizing the application by creating an eager-fetch diagram between these objects. However ...

Java - Learn the techniques for extracting both numerical values and characters from a given string

I'm trying to solve a problem with my calculator. I need to parse the integer from a string and then calculate the result. I believe subtraction should be done first, but I'm unsure of the correct pattern to follow. Is there a specific way to do ...

Switching an input field from readonly to editable in ASP.NET Core

MODAL <div class="modal fade" id="residentModal" tabindex="-1" role="dialog" aria-labelledby="residentModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg& ...

List of nested objects converted into a flat array of objects

Looking to transform a data structure from an array of objects containing objects to an objects in array setup using JavaScript/Typescript. Input: [ { "a": "Content A", "b": { "1": "Content ...

Navigate to the top of a Bootstrap accordion when it is expanded

Recently, I've been working on a small blog and I want to make consecutive blog posts accessible from within an accordion. This will allow users to easily skim through post titles, select the one they find interesting, read it, and seamlessly go back ...

Using Firebase collection inside an Angular constant

Currently, I am working on a Datatable using ng-bootstrap that utilizes a static array to display data. There are 3 main files involved: In the "country.ts" file, the necessary values are declared: export interface Country { id: number; name: string; ...

Get the file using jQuery ajax post request

Currently, I am attempting to export the data from my web page and download it as an Excel file. However, despite receiving a successful response, the download does not initiate. $.ajax({ type: "POST", url: _url, contentType: 'multi ...

Selenium RC does not execute the test suite using a BAT file

I've run into an issue while trying to execute my test suite using Selenium RC through a BAT file. Initially, everything was working fine until yesterday morning when it suddenly stopped running my test suite. The problem seems to be related to the ...

PHP and AJAX enable the seamless transfer of large files to a server in chunks via remote upload. This process includes a time limit setting to ensure efficient

Over on StackOverflow, there's a thread dedicated to the topic of streaming large files to users in chunks. The answer provided includes code that demonstrates how to accomplish this. However, my focus is on figuring out a way to simply save the file ...

Transforming an object into an interface and utilizing the interface methods implemented in a different location

When working with Selenium, the code below can be used to capture screenshots: WebDriver driver = new FirefoxDriver(); File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(src, new File("D:\\TestNGScreenshots ...

Is it achievable to remove the wrapper from elements using jQuery?

Is it possible to modify this markup without altering core files in the CMS? I have a particular structure that I would like to adjust using jQuery for a temporary solution. <div class="homepage-boxes"> <div class="row-fluid"> < ...

Establishing communication between a parent window and a popup window that have distinct domains

I'm currently developing a browser extension using JavaScript. My main tasks include: Sending javascript objects from a webpage located at "foo.com" to a popup page on "bar.com" For example, from "foo.com/some_page/" to "bar.com/another_page.htm ...

Image created from BitmapData stroke

Having trouble creating a sprite from BitmapData? It seems that when working with a rectangular shape, everything runs smoothly. However, when dealing with just a line, the sprite ends up empty. bmd = this.game.add.bitmapData(this.line.width, this.line. ...

Mastering the art of properly connecting Angular HttpPromise

Recently, I encountered an angular Service containing a crucial function: service.getItemByID = function(id) { var hp = $http({method: "GET", url: "service/open/item/id", headers: {"token": $rootScope.user.token}, para ...

Using Javascript regex to remove spaces inside parentheses

Can you provide the specific Javascript regex code for removing spaces only within parentheses? Take for instance: balance( 11010000 ) / balance( 11050000 ) The desired output should be: balance(11010000) / balance(11050000) ...

Issue: Please avoid using HTML tag <img>. Instead, utilize the Image component from 'next/image' - Next.js when working with styled components

While working with Next.js, I encountered an issue with the Image component. Unlike a regular HTML tag, the Image component requires a layout and doesn't offer the same level of control. Additionally, I found that it couldn't be used with framer ...