Exploring advanced mathematical calculations in QtQuick Qml with JavaScript for handling large numbers

I need to calculate the orbit of the Sun around the Galaxy. The mathematical formula I am using is ((241828072282107.5071453596951 * 666) * 2) * 3.14159265359. In QML JavaScript, I received the answer 1011954093357316100, but the correct answer is 1011954093357316200, off by 100 units.

galaxyRadius="241828072282107.5071453596951";

currentTrackNumber=666; // Track Number like on a Record

pIe="3.14159265359"; // not the same as Math.PI

I had to keep the numbers as strings because converting them to floats would lose precision. Converting an old bash script to JavaScript, I realized it worked fine with bc but not with Math.

I tried the following:

orbitDist = ((( Number.parseFloat(galaxyRadius).toPrecision(20) * currentTrackNumber) * 2) * Number.parseFloat(pIe).toPrecision(12) );

The results are the same as:

orbitDist = ((( galaxyRadius * currentTrackNumber) * 2) * pIe );

Compared to the bash result:

echo "$(bc <<< "scale=13;((241828072282107.5071453596951 * 666) * 2) * 3.14159265359")"

Bash is accurate while JavaScript is inaccurate by almost 100 units. This discrepancy is concerning, especially since I have many numbers that are slightly off. A 100-unit difference is not acceptable.

I prefer to work with integers rather than exponents. The values are stored in a database as strings, so I just need the math to be precise.

This is a QtQuick, QML, Felgo App using Qml and JavaScript, designed to run on various platforms. My next step is to consider C++ or a math library that suits this project. A JavaScript or QML wrapper library for C++ would be ideal. I have researched JavaScript libraries for the web, but they require extensive modifications for Qml. I am looking for a solution that works seamlessly.

Answer №1

In the current state, JavaScript only supports bignum for integers (BigInt). Therefore, I convert the numbers to BigInt before performing calculations and keep track of the decimal part to convert back to float.

const galaxyRadius="241828072282107.5071453596951";

const currentTrackNumber=666; // Track Number like on a Record

const pIe="3.14159265359"; // not the same as Math.PI

const orbitDist = ((( galaxyRadius * currentTrackNumber) * 2) * pIe );
console.log(orbitDist)

//// My approad

//Put all number into an array
var arrToMul = [galaxyRadius,currentTrackNumber, 2, pIe]

// Function multiple all item in array with BigInt format
function mulBigInt(arr) {
  return arr.reduce(function (acc, e) {
    return BigInt(e) * acc;
  }, BigInt(1));
}; 

// Function get length of decimal part
function decLength(str) {
  var dec = str.toString().split('.')[1];
  return dec ? dec.length : 0;
}; 

// Function remove point in string to convert float to int
function rmPoint(strNum) {
  return strNum.toString().replace('.', "");
}; 

// Main function
function cal(arr) {
  // Get total decimal part length of all number
  var pointSize = arr.reduce(function (acc, e) {
    return acc + decLength(e);
  }, 0); 
  
  // convert the all item to int (type string)
  var newArr = arr.map(function (e) {
    return rmPoint(e);
  }); 
  // Add point to reconvert BigInt to float(string actually)
  var tmp = mulBigInt(newArr).toString().split('');
  tmp.splice(tmp.length - pointSize, 0, '.'); 
  
  // Return float result with string format
  return tmp.join('');
};
const rs = cal(arrToMul)
console.log(rs, 'converted to BigInt:')

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

Using jq and node.js to translate AWS EC2 tags

Seeking assistance with transforming this array of EC2 tags using jq and node.js: [ { Key: 'Name', Value: 'xxx' }, { Key: 'role', Value: 'yyy' } ] I want to transform it to: { name : 'xxx', ro ...

Instructions for making a crossword-inspired grid using a high quantity of divs or alternative elements

I am looking to create a grid on the screen of a web browser or mobile device, with each grid item containing just one letter. It's similar to a crossword puzzle, but taking up most of the screen. I've tried using divs for this purpose, but it se ...

Trouble with executing AJAX for API call

My current project is built on CI3 and I have created an API that belongs to a different domain than the application itself. $.ajax({ url: "http://www.example.com/restapi/index.php/api/user", type: "GET", data: {"user_id": user_id} ...

Unable to modify the appearance of an HTML element when injected via a Chrome extension

I am currently developing a unique chrome extension that uses Ajax to inject custom HTML into the current tab. This extension appends a <div> element to the body, and now I need to manipulate it using JavaScript. Specifically, I want it to dynamical ...

Looking to adjust the API response to fit the necessary JSON format for an Angular project?

A modification is needed in the API response to align with the required JSON format provided below. The current responses and the desired format are detailed for reference. Assistance is appreciated. The current representation of individual's data ne ...

Create your own AngularJS directive for displaying or hiding elements using ng-show/ng

Caution: Angular rookie in action. I'm attempting to craft a personalized widget that initially displays a "Reply" link, and upon clicking it, should hide the link and reveal a textarea. Here's my current progress, but unfortunately, it's n ...

Choose an XPath formula that will target every single element, text node, and comment node in the original sequence

How can we write an XPath expression that selects all elements, text nodes, and comment nodes in the order they appear in the document? The code below selects all elements but not text nodes and comment nodes: let result = document.evaluate('//*&apo ...

Include an additional icon without replacing the existing one on the mouse cursor

I am looking for a way to enhance the user experience by adding an icon that appears when hovering over an HTML element, serving as a subtle hint that the user can right-click. Instead of replacing the default cursor, which varies across platforms and doe ...

Is it possible to include additional information when creating a subscription for a customer on Stripe using Node.js

I am facing an issue with adding metadata to the customer object during the creation of a new subscription/customer using Stripe. The problem lies in the fact that the metadata is not being saved to the customer object. I have checked the logs/events in St ...

Determining the Next Available Date from JSON Data

I have a task of using a JSON response from the Eventbrite API to showcase the upcoming event tour date. The goal is to automatically calculate this date based on the current time, identifying the next event after the current moment. Below is the JSON res ...

How should I proceed if I encounter an npm error stating that cb() was never called?

Hey everyone. I keep encountering an issue with npm whenever I attempt to install packages. I am receiving the following error message: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ERR! <h ...

Transferring the selected radio button from one HTML page to another without using PHP

I'm looking to transfer radio button data from the first HTML to the second using Pure JavaScript Feel free to use jQuery if needed. jQuery was used 1st HTML <body> <label for="1"> <input type="radio" name="num" id="1" checked="che ...

Exploring the Differences Between Next.js Script Components and Regular Script Tags with async and defer Attributes

Can you explain the distinctions between the next js <Script /> component rendering strategies such as afterInteracive, beforeInteractive, and lazyLoad, as opposed to utilizing a standard <script /> tag with attributes like async and defer? ...

Tips for utilizing a switch statement

I'm a beginner in JavaScript and recently learned about the switch statement. I have an exercise where I need to convert numbers 1-10 into words like "one", "two", "three"... This is what I have tried so far: function sayNum(){ let numberArray = [ ...

Automatically identify the appropriate data type using a type hint mechanism

Can data be interpreted differently based on a 'type-field'? I am currently loading data from the same file with known type definitions. The current approach displays all fields, but I would like to automatically determine which type is applicab ...

Update the state when a button is clicked and send a request using Axios

Currently in my front end (using react): import '../styles/TourPage.css'; import React, { Component } from 'react'; import axios from 'axios' class TourPage extends Component { constructor(props) { super(p ...

Some images fail to load on Ember in the production environment

I am facing an issue with my Ember-cli 1.13 application where all images are loading correctly except those in a specific component. The component is named "list-item" and is defined as follows: {{list-item url="list-url" name="List Name" price="240"}} I ...

Utilize JavaScript to iterate through a JSON object and retrieve the indices that meet the specified criteria

While I found a previous answer that somewhat addresses my issue, I am seeking guidance on how to return an array of the indexes where a specific value appears. For example, if **18A38** is the target value, it should return the positions [1,3]. The sampl ...

Convert a JSON array into a JavaScript array?

Similar Question: How can I extract property values from a JavaScript object into an array? I am receiving a JSON array from a basic server and need to parse it into JavaScript for use in my web application. What is the best way to convert a JSONP ar ...

Displaying content in a hidden div on click event

I am part of a volunteer group for prostate cancer awareness and support, and our website features multiple YouTube videos that are embedded. However, the page has been experiencing slow loading times due to the number of videos, despite them being hidden ...