Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.9 kB
2
Indexable
import java.util.ArrayList;
import java.util.List;

public class PhysicsProblemSolver {

    public static double calculateGravitationalForce(double x, double m1, double m2, double d) {
        double G = 6.67e-11;
        return G * m1 * m2 / Math.pow((d - x), 2);
    }

    public static double sumForcesFromLeft(double x, List<Double> xList, List<Double> mList) {
        int n = xList.size();
        double fSum = 0;
        for (int i = 0; i < n; i++) {
            if (xList.get(i) < x) {
                fSum += calculateGravitationalForce(x, mList.get(i), 1, xList.get(i));
            }
        }
        return fSum;
    }

    public static double sumForcesFromRight(double x, List<Double> xList, List<Double> mList) {
        int n = xList.size();
        double fSum = 0;
        for (int i = 0; i < n; i++) {
            if (xList.get(i) > x) {
                fSum += calculateGravitationalForce(x, mList.get(i), 1, xList.get(i));
            }
        }
        return fSum;
    }

    public static List<Double> findBalance(List<Double> xList, List<Double> mList) {
        int n = xList.size();
        List<Double> balancePoints = new ArrayList<>();
        for (int i = 0; i < n - 1; i++) {
            double a = xList.get(i);
            double b = xList.get(i + 1);
            double tol = 1e-9;
            int maxIter = 100;
            int iter = 0;
            while (Math.abs(a - b) > tol && iter < maxIter) {
                double c = (a + b) / 2;
                if (sumForcesFromLeft(c, xList, mList) == sumForcesFromRight(c, xList, mList)) {
                    break;
                } else if (sumForcesFromLeft(c, xList, mList) > sumForcesFromRight(c, xList, mList)) {
                    a = c;
                } else {
                    b = c;
                }
                iter++;
            }
            balancePoints.add((a + b) / 2);
        }
        return balancePoints;
    }

    public static void main(String[] args) {
        List<Double> xList1 = new ArrayList<>();
        xList1.add(1.0);
        xList1.add(2.0);

        List<Double> mList1 = new ArrayList<>();
        mList1.add(1.0);
        mList1.add(1.0);

        List<Double> balancePoints1 = findBalance(xList1, mList1);

        System.out.print("#1 ");

        for (Double point : balancePoints1) {
            System.out.printf("%.10f ", point);
        }

        System.out.println();

        List<Double> xList2 = new ArrayList<>();
        xList2.add(1.0);
        xList2.add(2.0);

        List<Double> mList2 = new ArrayList<>();
        mList2.add(1.0);
        mList2.add(1000.0);

        List<Double> balancePoints2 = findBalance(xList2, mList2);

        System.out.print("#2 ");

        for (Double point : balancePoints2) {
            System.out.printf("%.10f ", point);
        }

        System.out.println();
    }
}