用两个比例将给定数字除以该数字的一个分量的算法

时间:2016-09-18 05:18:35

标签: java algorithm linear-programming

请帮助我理解用于以下问题的JAVA算法或技术。
有三个组成部分
a = n * r / 100
r =(a * 100)/ n
n =(a / r)* 100

需要划分& n以这样的比例分成两部分:r应该在0.012和2.000之间。

实施例:
详细信息
n = 10,r = 0.8,a = 10 * 0.8 / 100 = 0.08

下面应该是n,r和a的值 r应介于0.012和2.000之间 n和r也可以是负数。

1)n = 6,r = 0.2,a = n * r / 100 = 10 * 0.2 / 100 = 0.012

2)n = 4,r =(a * 100)/ n = 0.068 * 100/4 = 1.7,a = 0.068

3 个答案:

答案 0 :(得分:0)

我想我现在已经知道了:给定n,a和r你想找到n1,a1,r1,n2,a2和r2,这样n1 + n2 = n,a1 + a2 = a,r1 * n1 = 100 * a1,r2 * n2 = 100 * a2,0.012 <= r1 <= 2.0且r2相同。它是否正确? 6个未知数,4个方程和4个不等式,可以很容易地给出无限多的解。

如果输入满足r * n = 100 * a且n至少为2,则可以找到许多解决方案:

    r = a * 100 / n;
    for (int n1 = 1; n1 < n; n1++) {
        double proportion = (double) n1 / (double) n;
        System.out.println("[1] n = " + n1 + " a = " + a * proportion + " r = " + r);
        proportion = 1 - proportion;
        System.out.println("[2] n = " + (n - n1) + " a = " + a * proportion + " r = " + r);
    }

如果输入不符合等式,那就变得比较棘手了,据我所知,可能有0或无限多的解决方案。

免责声明:我记不起我年轻时所学到的线性编程,所以我不会尝试任何一种。

编辑:精炼版本,忽略来自输入的r,仅打印指定范围内的r的解决方案,但可能会打印两倍于之前的解决方案,这已经太多了。

    // without loss of generality assume n1 <= n2
    for (int n1 = 1; n1 <= n / 2; n1++) {
        int n2 = n - n1;
        // a1 should be >= rMin * n1 / 100 and also = a - a2, that is >= a - rMax * n2 / 100
        double a1Min = Math.max(rMin * n1 / 100, a - (rMax * n2 / 100));
        double a1Max = Math.min(rMax * n1 / 100, a - rMin * n2 / 100);
        if (a1Min <= a1Max) {
            // print solution with a1 = a1Min
            System.out.println("[1] n = " + n1 + " a = " + a1Min + " r = " + 100 * a1Min / n1);
            double a2 = a - a1Min;
            System.out.println("[2] n = " + n2 + " a = " + a2 + " r = " + 100 * a2 / n2);
            // print solution with a1 = a1Max
            System.out.println("[1] n = " + n1 + " a = " + a1Max + " r = " + 100 * a1Max / n1);
            a2 = a - a1Max;
            System.out.println("[2] n = " + n2 + " a = " + a2 + " r = " + 100 * a2 / n2);
        }
    }

答案 1 :(得分:0)

感谢@Ole V.V提供解决方案。我在下面运行了您的代码

double a = 10000;//can be 40,000,000
double n = 50000;//can b 5,000,000,000
double r = a * 100 / n;//should be between a given range

但是,在输出中,“r”对于每次迭代始终是常量(20.0) 我们实际上需要在给定范围之间的r,并且[1]和[2]应该是不同的 代码实际上只应打印n1,a1,r1和n2,a2,r2,其中“r”落在给定范围的“r”之间 对于更大数量的“a”和“r”,您的代码将丢失内存。

答案 2 :(得分:0)

使用三角测量解决了问题。谢谢大家的帮助。