Last active
April 19, 2018 10:01
-
-
Save 3014zhangshuo/768b84c2455387a816fb22daa59dc24d to your computer and use it in GitHub Desktop.
一元三次方程解
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class @CubicEquations #加入 @ 跨作用域 绑定外层 this | |
constructor: (@a, @b, @c, @d) -> | |
@init() | |
@calc() | |
@result() | |
get_cube_root = (value) -> | |
if value < 0 | |
-Math.pow(-value, 1/3) | |
else if value > 0 | |
Math.pow(value, 1/3) | |
else | |
0 | |
init: -> | |
@A = @b * @b - 3 * @a * @c | |
@B = @b * @c - 9 * @a * @d | |
@C = @c * @c - 3 * @b * @d | |
@delta = @B * @B - 4 * @A * @C | |
A_and_B_equal_zero: -> | |
@x1 = -@b / (3*@a) | |
@x2 = @x1 | |
@x3 = @x1 | |
delta_equal_zero: -> | |
k = @B / @A | |
@x1 = -@b / @a + k | |
@x2 = @x1 | |
@x3 = @x1 | |
delta_greater_zero: -> | |
Y1 = @A * @b + 3 * @a * ( ( -@B + Math.sqrt(@delta) ) / 2 ) | |
Y2 = @A * @b + 3 * @a * ( ( -@B - Math.sqrt(@delta) ) / 2 ) | |
@x1 = ( -@b - ( get_cube_root(Y1) + get_cube_root(Y2) ) ) / (3 * @a) | |
@x2 = 0 | |
@x3 = 0 | |
# @x2 @x3 是复数 | |
delta_less_zero: -> | |
T = (2 * @A * @b - 3 * @a * @B) / (2 * Math.sqrt(@A * @A * @A)) | |
angle = Math.acos(T) / 3 | |
@x1 = (-@b - 2 * Math.sqrt(@A) * Math.cos(angle/3)) / (3 * @a); | |
@x2 = (-@b + Math.sqrt(@A) * (Math.cos(angle/3) + Math.sqrt(3) * Math.sin(angle/3))) / (3 * @a) | |
@x3 = (-@b + Math.sqrt(@A) * (Math.cos(angle/3) - Math.sqrt(3) * Math.sin(angle/3))) / (3 * @a) | |
calc: -> | |
if @A == 0 && @B== 0 | |
@A_and_B_equal_zero() | |
else if @delta == 0 | |
@delta_equal_zero() | |
else if @delta > 0 | |
@delta_greater_zero() | |
else | |
@delta_less_zero() | |
result: -> | |
@result = Math.max(@x1, @x2, @x3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment