package inventory;

import java.text.DecimalFormat;

/**
 * Модель задачи о торговле несохраняемого товара с заданным распределением спроса.
 * F(x) = sqrt((x-a)/(b-a));  f(x) = 0.5 * sqrt((b-a)/(x-a));
 * 
 * Created on 2022-03-23 19:50:16
 * @author Alexander Mikhailovich Kovshov
 */
public class RandomDemandFab {
    
    public static void main(String[] args) {
        System.out.println("Hello!");
        double x;           // дневной запас товара
        double p = 50;      // отпускная цена
        double q = 30;      // закупочная цена
        double r = 10;      // остаточная цена
        double a = 2;       // наименьшай спрос
        double b = 6;       // наибольший спрос
        int n = 10000000;   // число испытаний в численном опыте
        for (x = a; x <= b; x += 1) {
            process(x, p, q, r, a, b, n);
        } 
        x = (p - q) / (p - r); 
        x *= x * (b-a);   x += a;
        System.out.println("максимум при х: " + x);
        process(x, p, q, r, a, b, n);
        System.out.println("a: " + a + ";   b: " + b);
    }

    /**
     * Симуляция торговли со случайным спросом несохраняемого товара.
     * @param xдневной заказ.
     * @param pотпускная цена
     * @param qзакупочная цена
     * @param rостаточная цена
     * @param aнаименьшай спрос
     * @param bнаибольший спрос
     * @param n - число испытаний в численном опыте.
     */
    public static void process(double x, double p, double q, double r, double a, double b, int n) {
        double profit = 0;
        
        for (int i = 0; i < n; i++) {
            double y = Math.random();
            y *= y * (b - a); y += a;
            profit -= q * x;
            if (y < x) {
                profit += p * y;
                profit += r * (x - y);
            } else {
                profit += p * x;
            }
        }
        profit /= n;
        double h = (p - q) * x - (p - r) * (x - a) * Math.sqrt((x - a) / (b - a)) * 2 / 3;
        DecimalFormat df = new DecimalFormat("  00.0000000000; -00.#########"); 
        System.out.println("x: " + x + ";  среднедневная прибыль: " + df.format(profit) + ";  по формуле: " + df.format(h));
    }
}