Loop through the coefficients of a polynomial created from a string using JavaScript

Summary: Seeking a method to generate a polynomial from specified coordinates, enabling coefficient iteration and optional point evaluation

I am currently developing a basic JavaScript/TypeScript algorithm for KZG commitments, which involves multiplying coefficients of a polynomial derived from a given string with the Structured Reference String (SRS) raised to the appropriate power.

Essentially, I need to loop through all the coefficients of this newly created polynomial (or at least that's my current understanding– any suggestions are welcome).

My objective is as follows:

  1. Input a string
  2. Convert the string into XY-coordinates on a plane
  3. Determine the polynomial passing through these coordinates
  4. **Iterate over the polynomial’s coefficients **<-- where I'm encountering a roadblock
  5. (optional) Evaluate the polynomial at a specific point Z <-- it would be ideal if this functionality can coexist with the previous requirement

I’m facing challenges at step 4).

While I know how to build a polynomial from a given string in JS/TS using Lagrange Interpolation, extracting its coefficients proves difficult. These coefficients are essential for subsequent multiplication with SRS.

Below is my Lagrange Interpolation algorithm - capable of solving 5), but lacking an apparent method for obtaining exact coefficients:

type Point = { x: number; y: number };

function lagrangeInterpolation(points: Point[], newX: number) {
  const n = points.length;
  let newY = 0;

  for (let i = 0; i < n; i++) {
    let { x, y } = points[i];

    let term = y;
    for (let j = 0; j < n; j++) {
      if (i !== j) {
        let { x: xj } = points[j];
        term = (term * (newX - xj)) / (x - xj);
      }
    }
    newY = newY + term;
  }

  return newY;
}

Would another interpolation algorithm facilitate precise coefficient calculations?

I couldn't locate any JS libraries addressing this issue directly. The closest contenders were:

  • polynomial -> drawback: lacks a built-in method for returning coefficients or processing a Lagrange-like polynomial for regex-based coefficient extraction.
  • nerdamer-prime -> downside: can simplify any polynomial but doesn’t guarantee term order by x power, complicating coefficient retrieval via regex; also lacks direct coefficient access.

Answer №1

If you're looking to implement Lagrange interpolation, one of the methods you can use is based on matrices as explained by @guest in this reference: Coefficients of Lagrange polynomials.

To accomplish this, you will require a function that can compute the determinant of a matrix. The Gaussian elimination method is commonly used for this purpose.

Below is a sample implementation using JavaScript:

function determinant(mat) {
    const n = mat.length;
    let det = 1;
    for (let r = 0; r < n; r++) {
        let r2 = r;
        while (!mat[r2][r]) {
            r2++;
            if (r2 >= mat.length) return 0;
        }
        const row = mat[r2];
        if (r2 !== r) { // Swap rows
            mat[r2] = mat[r];
            mat[r] = row;
            det = -det;
        }
        let div = row[r];
        if (!div) return 0;
        det *= div;
        for (let c = r; c < n; c++) row[c] /= div;
        for (let r2 = r+1; r2 < n; r2++) {
            const row2 = mat[r2];
            const mul = row2[r];
            for (let c = r; c < n; c++) {
                row2[c] -= mul * row[c]; 
            }
        }
    }
    return det;
}

function lagrangeInterpolationCoefficients(points) {
    const lagrangeDet = (j) => determinant(points.map((_, i) => 
        points.map(([a, b]) => i == j ? b : a ** i)
    ));
    const denom = lagrangeDet(-1);
    return points.map((_, j) => lagrangeDet(j) / denom);
}

const coefficientsToFunction = (coefficients) =>
    x => coefficients.reduce((sum, coeff, i) => sum + coeff * x**i, 0);

const coefficientsToString = (coefficients) =>
    coefficients.map((coeff, i) => `${coeff}x^${i}`)
                .reverse().join(" + ")
                .replace(/x\^0|\^1\b|\b0x\^\d+/g, "")
                .replaceAll("+ -", "- ");

const points = [[0, -1], [1, 1], [3, 8], [4, 10]];
const coefficients = lagrangeInterpolationCoefficients(points);
console.log("f(x) =", coefficientsToString(coefficients));
const f = coefficientsToFunction(coefficients);

for (const [x, y] of points) {
    console.log({x, y, "f(x)": f(x)});
}

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

How can one HTML form be used to request a unique identifier from the user, retrieve a record from the database, parse it into JSON format, and then populate an HTML page form using the

As someone who isn't an expert in any specific coding language, I have a knack for piecing things together to make them work. However, my current challenge is stretching my technical abilities a bit too far. Here's what I'm trying to achieve ...

When attempting to add a variable using the next() function, I encountered an error with the BehaviorSubject. The error message displayed was "this.count.next is not a function"

In my Angular service, there is a variable called count that I need to monitor for updates. Whenever this count variable is updated, I want to assign its new value to another variable in a separate component. import {BehaviorSubject} from "rxjs/BehaviorSu ...

Best Practices for Handling Pre-State Setting Mutations in Flux Design Pattern

Currently, I am developing a Vue application utilizing Vuex and following the Flux design pattern. I have encountered what seems to be an inefficient practice of duplicating code in small increments. I am hopeful that this is just a misunderstanding on my ...

Concerning the issue of components not loading correctly when using Angular with Lazy Loading Routing

Encountering an unusual issue while utilizing lazyload routing in our application! Within AppModule, there is TopModule followed by DashboardModule, all being loaded lazily. When localhost:4200/dashboard is accessed, the loading sequence is AppModule, To ...

Interacting between Angular controllers and services to efficiently showcase JSON information

Recently, I started working with Angular 1.5+ and I'm facing some challenges with the basics, particularly when it comes to displaying data from a JSON file on the DOM. Although I can fetch the data successfully (at least I think so, as it console lo ...

What is the best method to determine the currency associated with the code in dinero.js?

Is there an easy way to locate the dinero currency in the dinero.js/currencies package using its code? For example, a function called getCurrency that accepts a string as input and outputs the corresponding dinero currency. ...

When using $dialogs.create on my website, a popup form appears with specific formatting limitations dictated by the defining code

When a user clicks a button on my website, a function in the controller is triggered. Here is the function that runs when the button is pressed: $scope.launch = function(idOfSpotOfInterest, schedOfSpotOfInterest){ var dlg = null; dlg = $dialogs. ...

What is the best way to extract a single item from an array in Javascript and assign it to a different variable

I am currently dealing with an array of objects structured like this: contacts: [ { id: 1, name: "John Doe", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="066c696e6846616b676f6a2865696b">[emai ...

Reactjs is having issues with Datatable functions

I am making use of the Datatable Library for creating tables easily. After fetching data with the Fetch API and rendering it to the table, everything seems to work smoothly. However, I am facing issues with DataTable Functions such as sorting, searching, ...

What is React.js's approach to managing CSS files?

Currently, I am enrolled in Bootcamp at Scrimba where they utilize an online platform for teaching various courses. One of the topics covered is React and involves working with CSS files. When working on my local machine, I typically use the index.css file ...

"Patience is key as we await the resolution of a promise within the confines of an emitter

My goal is to wait for the promise to be resolved before continuing when the someevent event is fired. However, even though I use a then in my code snippet below, it seems that the process shuts down before the slowFunctionThatReturnsPromise is resolved, ...

In JavaScript, the function is unable to access elements within an iteration of ng-repeat

I am using ng-repeat to display datepickers that are powered by flatpickr. To make this work, a script needs to be added on the page for each input element like so: <script> $('[name="DOB"]').flatpickr({ enableTime: false, dateForm ...

Disabling the last control in a formGroup when sorting an array with Angular

I am facing an issue with sorting an array based on a numeric control value inside a formGroup nested in another array: const toSort = [ ['key2', FormGroup: {controls: {order: 2}}], ['key1', FormGroup: {controls: {order: 1}}] ] ...

Replace jQuery CSS with standard CSS without using !important to override styles

Recently, I encountered a puzzling situation: I have an element with the following CSS properties ($(this) represents the cloned object): clone.css({ 'width': $(this).width() + 'px', 'height': $(this).height() + ' ...

Are you able to locate <td>s with identical classes using just a portion of the string?

There are multiple classes in the <td>s of my table. I am looking to identify each <td> that contains a specific string. For instance: <table> <tr> <td class="hello there">foo</td> <td class=" ...

Having trouble updating the DataTable with extra details retrieved from a new URL

I'm currently utilizing the DataTable plugin. After loading the DataTable, my aim is to reload the table, while keeping the existing content intact, and adding information gathered from a separate json file. However, I'm encountering an issue wh ...

Utilizing JSON format, handling special characters, and storing data in a database

My friend approached me with a question and although I wanted to offer immediate help, I realized that seeking advice from others may provide better solutions. Situation: Imagine there is a Form that includes a RichText feature: DHTMLX RichText (). This R ...

What is the best way to eliminate excess space on the right side in Bootstrap 4 while in mobile view?

I'm struggling to understand why this layout is not responsive on mobile devices, triggering a bottom scroll bar at around 616px. I'm looking for a solution to hide the scroll bar at least until 414px for iPhones and other smartphones. I've ...

Tips for getting the jQuery accordion to return smoothly to its original position (instead of stacking on top of each other)

I'm a complete beginner at this and could really use some assistance. Here's my JS Fiddle: http://jsfiddle.net/hAZR7/ The problem I'm facing seems to be more related to logic or math, as the animation works fine when starting and moving to ...

Dynamic Lookup Material Table

I am currently using MaterialTable imported from "material-table". import MaterialTable from "material-table" I am attempting to make the 'lookup' for an editable table dynamic. My goal is to have a drop-down with edit options when I make change ...