Well here is again, the refactored version.

"The idea is to have a class to calculate quadratic equations.
This second draft still only calculates real roots (leaving aside imaginary
roots).
But thanks to Damien Cassou I think it has a better style.

A QuadraticEquation is a class used to solve Quadratic Equations of the
form: ax^2 + bx + c = 0, where a is not 0.

You can set the coefficients using the following method
setQuadraticCoefficient:  linearCoefficient:  constant: "

Object subclass: #QuadraticEquation
        instanceVariableNames: 'quadraticCoefficient linearCoefficient constant
roots'
        classVariableNames: ''
        category: 'IS-Math'

"I create accessors (only getters for each term) and then the following
method to set the terms"

QuadraticEquation>>setQuadraticCoefficient: aNumber1 linearCoefficient:
aNumber2 constant: aNumber3
        quadraticCoefficient := aNumber1.
        linearCoefficient := aNumber2.
        constant := aNumber3
        


QuadraticEquation>>calculateRoots
        | checkNegative |
        checkNegative := linearCoefficient  squared - ( 4 * 
quadraticCoefficient  *
constant).

        checkNegative  >= 0 
                ifFalse: [ Error signal: 'Negative square root']
                ifTrue: [ ^ self solveRoots: checkNegative]
        
QuadraticEquation>>solveRoots: aTerm
        | rootA rootB |
        roots := OrderedCollection new.
        rootA := (linearCoefficient  negated + aTerm sqrt) / (2 *
quadraticCoefficient).
        rootB := (linearCoefficient  negated  - aTerm sqrt) / (2 *
quadraticCoefficient).
        roots add: rootA; add: rootB.
        ^ roots
                        
                        
"       Example:  -3x^2+2x+2=0
        an OrderedCollection(-0.5485837703548636 1.2152504370215302)

        print(it)

        | anEquation |
        anEquation := QuadraticEquation new.
        anEquation setQuadraticCoefficient: -3 linearCoefficient: 2 constant: 
2. 
        anEquation calculateRoots."

Thanks again
Best,
Nacho



-----
Nacho
Smalltalker apprentice.
Buenos Aires, Argentina.
--
View this message in context: 
http://forum.world.st/Question-on-style-tp4752165p4752262.html
Sent from the Pharo Smalltalk Users mailing list archive at Nabble.com.

Reply via email to