简体   繁体   English

Mathjs自定义求和函数

[英]Mathjs custom sum function

i am trying to implement my own custom sum function. 我正在尝试实现自己的自定义函数。 The goal is to have a function called "sumFromTo" that takes 4 parameter * iteratorname * from * to * function 目标是有一个名为“sumFromTo”的函数,它从*到*函数中获取4个参数* iteratorname *

where "function" can be some other function and where the solution is to sum all. 其中“功能”可以是其他功能,解决方案是将所有功能相加。 For example 例如

// works 
  sumFromTo(i,1,10,i+1)  // = 65

But if i wrap this into an other function it will break, because mathjs doesn't know "x" 但是,如果我把它包装成另一个函数它会破坏,因为mathjs不知道“x”

// works not because x is undefined
test(x) = sumFromTo(i,1,x,i+1) 
test(10)

My Import looks like this: 我的导入看起来像这样:

function sumFromTo(iteratorName, from, to, toString, f) {
    var total = 0;
    var toVal = typeof to == "number" ? to : to.length;
    for (var iterator = from; iterator <= toVal; iterator++) {
        mathScope[iteratorName] = iterator;
        mathScope[toString + "_" + iterator] = to[iterator];
        total += math.eval(f, mathScope);
    }
    return total;
}
sumFromTo.transform = function (args, math, scope) {
    /*   Iterator    */
    var iteratorName = "notfound";
    if (args[0] instanceof math.expression.node.SymbolNode) {
        iteratorName = args[0].name;
    } else {
        throw new Error('First argument must be a symbol');
    }

    /*    Startvalue of Iterator    */
    if (args[1] instanceof math.expression.node.ConstantNode) {
        if (args[1].value == 0) {
            throw new Error('Sum must counting from >=1: 0 given');
        }
    }

    /*    to: Array to loop    */
    if (args[2] instanceof math.expression.node.SymbolNode) {
        var toString = args[2].name;
    }

    /*    compile    */
    var from = args[1].compile().eval(scope);
    scope[iteratorName] = from;
    var to = args[2].compile().eval(scope);

    if (to.constructor.name == "Matrix") {
        to = to.toArray();
        scope[toString] = to;
    }else{
        if(typeof to == "object"){
            to = to.toArray();
        }
    }
    return sumFromTo(iteratorName, from, to, toString, args[3].toString());
};
sumFromTo.transform.rawArgs = true;
math.import({sumFromTo: sumFromTo}, {override: true});

I create a fiddle https://jsfiddle.net/o49p4zwa/2/ , maybe it's helpful to understanding my problem. 我创建了一个小提琴https://jsfiddle.net/o49p4zwa/2/ ,也许它有助于理解我的问题。

Does someone know what i am missing or what i am doing wrong? 有人知道我错过了什么或我做错了什么?

Thanks in advance!! 提前致谢!!

What you need is closure 你需要的是关闭

test = function(x) {
    sumFromTo(i,1,x,i+1) 
}
test(10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM