Skip to content

Instantly share code, notes, and snippets.

@SYZYGY-DEV333
Created October 3, 2018 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SYZYGY-DEV333/d2e364eacccd0ef6154e714f2e9b96dc to your computer and use it in GitHub Desktop.
Save SYZYGY-DEV333/d2e364eacccd0ef6154e714f2e9b96dc to your computer and use it in GitHub Desktop.
Nth root of A. `gst nth-root-a.st -a N A`
Number extend [
nthRoot: n [
|x0 m x1|
x0 := (self / n) asFloatD.
m := n - 1.
[true] whileTrue: [
x1 := ((m * x0) + (self/(x0 raisedTo: m))) / n.
((x1 - x0) abs) < ((x0 * 1e-9) abs)
ifTrue: [ ^ x1 ].
x0 := x1.
]
]
].
(((Smalltalk getArgv: 2) asNumber) nthRoot: ((Smalltalk getArgv: 1) asNumber)) displayNl.
@SYZYGY-DEV333
Copy link
Author

Pseudocode:

extend Number class {
  method nthRoot(n) {
    vars (x0 m x1);
    set x0 = float(self / n);
    set m = n - 1;
    while (true) {
      set x1 = ((m * x0) + (self / (x0 ^ m))) / n;
      if (abs(x1 - x0) < abs(x0 * 1e-9)) {
        return(x1);
      }
      set x0 = x1
    }
  }
}

println(nthRoot(sys.argv[1], sys.argv[2]));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment