Example usage for org.apache.commons.math3.analysis.polynomials PolynomialFunction derivative

List of usage examples for org.apache.commons.math3.analysis.polynomials PolynomialFunction derivative

Introduction

In this page you can find the example usage for org.apache.commons.math3.analysis.polynomials PolynomialFunction derivative.

Prototype

public UnivariateFunction derivative() 

Source Link

Document

Returns the derivative as a UnivariateFunction .

Usage

From source file:org.apache.solr.client.solrj.io.eval.PolyFitDerivativeEvaluator.java

@Override
public Object doWork(Object... objects) throws IOException {

    if (objects.length > 3) {
        throw new IOException("polyfitDerivative function takes a maximum of 3 arguments.");
    }// ww w . j  ava 2  s. com

    Object first = objects[0];

    double[] x = null;
    double[] y = null;
    int degree = 3;

    if (objects.length == 1) {
        //Only the y values passed

        y = ((List) first).stream().mapToDouble(value -> ((BigDecimal) value).doubleValue()).toArray();
        x = new double[y.length];
        for (int i = 0; i < y.length; i++) {
            x[i] = i;
        }

    } else if (objects.length == 3) {
        // x, y and degree passed

        Object second = objects[1];
        x = ((List) first).stream().mapToDouble(value -> ((BigDecimal) value).doubleValue()).toArray();
        y = ((List) second).stream().mapToDouble(value -> ((BigDecimal) value).doubleValue()).toArray();
        degree = ((Number) objects[2]).intValue();
    } else if (objects.length == 2) {
        if (objects[1] instanceof List) {
            // x and y passed
            Object second = objects[1];
            x = ((List) first).stream().mapToDouble(value -> ((BigDecimal) value).doubleValue()).toArray();
            y = ((List) second).stream().mapToDouble(value -> ((BigDecimal) value).doubleValue()).toArray();
        } else {
            // y and degree passed
            y = ((List) first).stream().mapToDouble(value -> ((BigDecimal) value).doubleValue()).toArray();
            x = new double[y.length];
            for (int i = 0; i < y.length; i++) {
                x[i] = i;
            }

            degree = ((Number) objects[1]).intValue();
        }
    }

    PolynomialCurveFitter curveFitter = PolynomialCurveFitter.create(degree);
    WeightedObservedPoints points = new WeightedObservedPoints();
    for (int i = 0; i < x.length; i++) {
        points.add(x[i], y[i]);
    }

    double[] coef = curveFitter.fit(points.toList());
    PolynomialFunction pf = new PolynomialFunction(coef);
    UnivariateFunction univariateFunction = pf.derivative();

    List list = new ArrayList();
    for (double xvalue : x) {
        double yvalue = univariateFunction.value(xvalue);
        list.add(yvalue);
    }

    return list;
}