読者です 読者をやめる 読者になる 読者になる

Javaで2次方程式を扱う

概要

2次方程式を扱うプログラム。

class MyquadraticEquation {
	private double a;// x^2の係数
	private double b;// x^1の係数
	private double c;// x^0の係数
	private double d;// 判別式の解
	private MySolution solution;// 解

	MyquadraticEquation(double a, double b, double c) {
		this.a = a;
		this.b = b;
		this.c = c;
		this.d = discriminant(a, b, c);
	}

	void solve(double a, double b) {
		if (d > 0) {
			MySolution mysl = new MySolution((double) (-1 * b + Math.sqrt(d))
					/ (2 * a), (double) (-1 * b - Math.sqrt(d)) / (2 * a));
			this.solution = mysl;
		}
		if (d == 0) {
			MySolution mysl = new MySolution((double) (-1 * b + Math.sqrt(d))
					/ (2 * a));
			this.solution = mysl;
		}
		if (d < 0) {
			MyComplex mc = new MyComplex(-b / 2 * a, Math.sqrt(-1 * d)
					/ (2 * a));
			MySolution mysl = new MySolution(mc);
			this.solution = mysl;
		}
	}

	double discriminant(double a, double b, double c) {
		this.d = b * b - 4 * a * c;
		return this.d;
	}

	public String toString() {
		return "[方程式" + a + "x^2+" + b + "x+" + c + "=0]" + "     [判別式=" + d
				+ "]";
	}

	MySolution getSolution() {
		solve(a, b);
		return solution;
	}
}

class MySolution {
	private String root_type;// 解の説明(「実数解」、「重解」、「虚数解」)
	private double root1;// (実数解の1つ目)
	private double root2;// (実数解の2つ目)
	private double root;// 重根
	private MyComplex solution;// 虚数解

	MySolution(double root1, double root2) {// 実数解を2つセットする、解の説明root_typeを「実数解」とする
		this.root1 = root1;
		this.root2 = root2;
		this.root_type = "実数解";
	}

	MySolution(double root) {// 重根をセットする、解の説明root_typeを「重根」とする
		this.root = root;
		this.root_type = "重根";
	}

	MySolution(MyComplex mc) {// 虚数解をセットする、解の説明root_typeを「虚数解」とする
		this.solution = mc;
		this.root_type = "虚数解";
	}

	public String toString() {
		String answer = null;
		if (this.root_type == "実数解") {
			answer = "実根 [" + this.root1 + "]   [" + root2 + "]";
		}
		if (this.root_type == "重根") {
			answer = "重根 [" + this.root + "]";
		}
		if (this.root_type == "虚数解") {
			answer = "虚数解 実部[" + this.solution + "]";
		}
		return answer;

	}
}

class MyComplex {
	private double real;// 実部
	private double imaginary;// 虚部

	MyComplex(double r, double im) {
		this.real = r;
		this.imaginary = im;
	}

	public String toString() {
		return "実部[" + real + "]" + "     虚部[" + imaginary + "]";
	}
}

public class MyQuadraticEquationTest_1 {
	public static void main(String[] args) {
		MyquadraticEquation mqe1 = new MyquadraticEquation(1.0, -5.0, 4);
		System.out.println(mqe1);
		System.out.println(mqe1.getSolution());

		MyquadraticEquation mqe2 = new MyquadraticEquation(1.0, -2.0, 1.0);
		System.out.println(mqe2);
		System.out.println(mqe2.getSolution());

		MyquadraticEquation mqe3 = new MyquadraticEquation(1.0, 0.0, 16.0);
		System.out.println(mqe3);
		System.out.println(mqe3.getSolution());

	}
}

実行結果

[方程式1.0x^2+-5.0x+4.0=0] [判別式=9.0]
実根 [4.0] [1.0]
[方程式1.0x^2+-2.0x+1.0=0] [判別式=0.0]
重根 [1.0]
[方程式1.0x^2+0.0x+16.0=0] [判別式=-64.0]
虚数解 実部[実部[-0.0] 虚部[4.0]]