Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Maintain the same structure and functionality when rewriting this code in C.
$epsilon=1E-10 function power($x,$e){ $ret=1 for($i=1;$i -le $e;$i++){ $ret*=$x } return $ret } function root($y,$n){ if (0+$n -lt 0){$tmp=-$n} else {$tmp=$n} $ans=1 do{ $d = ($y/(power $ans ($tmp-1)) - $ans)/$tmp $ans+=$d } while ($d -lt -$epsilon -or $d -gt $epsilon) if (0+$n -lt 0){return 1/$ans} else {return $ans} } root 625 2 root 2401 4 root 2 -2 root 1.23456789E-20 34 root 9.87654321E20 10 ((root 5 2)+1)/2 ((root 5 2)-1)/2
#include <stdio.h> #include <float.h> double pow_ (double x, int e) { int i; double r = 1; for (i = 0; i < e; i++) { r *= x; } return r; } double root (int n, double x) { double d, r = 1; if (!x) { return 0; } if (n < 1 || (x < 0 && !(n&1))) { return 0.0 / 0.0; } do { d = (x / pow_(r, n - 1) - r) / n; r += d; } while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10); return r; } int main () { int n = 15; double x = pow_(-3.14159, 15); printf("root(%d, %g) = %g\n", n, x, root(n, x)); return 0; }
Convert this PowerShell block to C#, preserving its control flow and logic.
$epsilon=1E-10 function power($x,$e){ $ret=1 for($i=1;$i -le $e;$i++){ $ret*=$x } return $ret } function root($y,$n){ if (0+$n -lt 0){$tmp=-$n} else {$tmp=$n} $ans=1 do{ $d = ($y/(power $ans ($tmp-1)) - $ans)/$tmp $ans+=$d } while ($d -lt -$epsilon -or $d -gt $epsilon) if (0+$n -lt 0){return 1/$ans} else {return $ans} } root 625 2 root 2401 4 root 2 -2 root 1.23456789E-20 34 root 9.87654321E20 10 ((root 5 2)+1)/2 ((root 5 2)-1)/2
static void Main(string[] args) { Console.WriteLine(NthRoot(81,2,.001)); Console.WriteLine(NthRoot(1000,3,.001)); Console.ReadLine(); } public static double NthRoot(double A,int n, double p) { double _n= (double) n; double[] x = new double[2]; x[0] = A; x[1] = A/_n; while(Math.Abs(x[0] -x[1] ) > p) { x[1] = x[0]; x[0] = (1/_n)*(((_n-1)*x[1]) + (A/Math.Pow(x[1],_n-1))); } return x[0]; }
Preserve the algorithm and functionality while converting the code from PowerShell to C++.
$epsilon=1E-10 function power($x,$e){ $ret=1 for($i=1;$i -le $e;$i++){ $ret*=$x } return $ret } function root($y,$n){ if (0+$n -lt 0){$tmp=-$n} else {$tmp=$n} $ans=1 do{ $d = ($y/(power $ans ($tmp-1)) - $ans)/$tmp $ans+=$d } while ($d -lt -$epsilon -or $d -gt $epsilon) if (0+$n -lt 0){return 1/$ans} else {return $ans} } root 625 2 root 2401 4 root 2 -2 root 1.23456789E-20 34 root 9.87654321E20 10 ((root 5 2)+1)/2 ((root 5 2)-1)/2
double NthRoot(double m_nValue, double index, double guess, double pc) { double result = guess; double result_next; do { result_next = (1.0/index)*((index-1.0)*result+(m_nValue)/(pow(result,(index-1.0)))); result = result_next; pc--; }while(pc>1); return result; };
Convert this PowerShell snippet to Java and keep its semantics consistent.
$epsilon=1E-10 function power($x,$e){ $ret=1 for($i=1;$i -le $e;$i++){ $ret*=$x } return $ret } function root($y,$n){ if (0+$n -lt 0){$tmp=-$n} else {$tmp=$n} $ans=1 do{ $d = ($y/(power $ans ($tmp-1)) - $ans)/$tmp $ans+=$d } while ($d -lt -$epsilon -or $d -gt $epsilon) if (0+$n -lt 0){return 1/$ans} else {return $ans} } root 625 2 root 2401 4 root 2 -2 root 1.23456789E-20 34 root 9.87654321E20 10 ((root 5 2)+1)/2 ((root 5 2)-1)/2
public static double nthroot(int n, double A) { return nthroot(n, A, .001); } public static double nthroot(int n, double A, double p) { if(A < 0) { System.err.println("A < 0"); return -1; } else if(A == 0) { return 0; } double x_prev = A; double x = A / n; while(Math.abs(x - x_prev) > p) { x_prev = x; x = ((n - 1.0) * x + A / Math.pow(x, n - 1.0)) / n; } return x; }
Convert this PowerShell block to Python, preserving its control flow and logic.
$epsilon=1E-10 function power($x,$e){ $ret=1 for($i=1;$i -le $e;$i++){ $ret*=$x } return $ret } function root($y,$n){ if (0+$n -lt 0){$tmp=-$n} else {$tmp=$n} $ans=1 do{ $d = ($y/(power $ans ($tmp-1)) - $ans)/$tmp $ans+=$d } while ($d -lt -$epsilon -or $d -gt $epsilon) if (0+$n -lt 0){return 1/$ans} else {return $ans} } root 625 2 root 2401 4 root 2 -2 root 1.23456789E-20 34 root 9.87654321E20 10 ((root 5 2)+1)/2 ((root 5 2)-1)/2
from decimal import Decimal, getcontext def nthroot (n, A, precision): getcontext().prec = precision n = Decimal(n) x_0 = A / n x_1 = 1 while True: x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1)))) if x_0 == x_1: return x_1
Rewrite the snippet below in VB so it works the same as the original PowerShell code.
$epsilon=1E-10 function power($x,$e){ $ret=1 for($i=1;$i -le $e;$i++){ $ret*=$x } return $ret } function root($y,$n){ if (0+$n -lt 0){$tmp=-$n} else {$tmp=$n} $ans=1 do{ $d = ($y/(power $ans ($tmp-1)) - $ans)/$tmp $ans+=$d } while ($d -lt -$epsilon -or $d -gt $epsilon) if (0+$n -lt 0){return 1/$ans} else {return $ans} } root 625 2 root 2401 4 root 2 -2 root 1.23456789E-20 34 root 9.87654321E20 10 ((root 5 2)+1)/2 ((root 5 2)-1)/2
Private Function nth_root(y As Double, n As Double) Dim eps As Double: eps = 0.00000000000001 Dim x As Variant: x = 1 Do While True d = (y / x ^ (n - 1) - x) / n x = x + d e = eps * x If d > -e And d < e Then Exit Do End If Loop Debug.Print y; n; x; y ^ (1 / n) End Function Public Sub main() nth_root 1024, 10 nth_root 27, 3 nth_root 2, 2 nth_root 5642, 125 nth_root 7, 0.5 nth_root 4913, 3 nth_root 8, 3 nth_root 16, 2 nth_root 16, 4 nth_root 125, 3 nth_root 1000000000, 3 nth_root 1000000000, 9 End Sub
Maintain the same structure and functionality when rewriting this code in Go.
$epsilon=1E-10 function power($x,$e){ $ret=1 for($i=1;$i -le $e;$i++){ $ret*=$x } return $ret } function root($y,$n){ if (0+$n -lt 0){$tmp=-$n} else {$tmp=$n} $ans=1 do{ $d = ($y/(power $ans ($tmp-1)) - $ans)/$tmp $ans+=$d } while ($d -lt -$epsilon -or $d -gt $epsilon) if (0+$n -lt 0){return 1/$ans} else {return $ans} } root 625 2 root 2401 4 root 2 -2 root 1.23456789E-20 34 root 9.87654321E20 10 ((root 5 2)+1)/2 ((root 5 2)-1)/2
func root(a float64, n int) float64 { n1 := n - 1 n1f, rn := float64(n1), 1/float64(n) x, x0 := 1., 0. for { potx, t2 := 1/x, a for b := n1; b > 0; b >>= 1 { if b&1 == 1 { t2 *= potx } potx *= potx } x0, x = x, rn*(n1f*x+t2) if math.Abs(x-x0)*1e15 < x { break } } return x }
Produce a language-to-language conversion: from R to C, same semantics.
nthroot <- function(A, n, tol=sqrt(.Machine$double.eps)) { ifelse(A < 1, x0 <- A * n, x0 <- A / n) repeat { x1 <- ((n-1)*x0 + A / x0^(n-1))/n if(abs(x1 - x0) > tol) x0 <- x1 else break } x1 } nthroot(7131.5^10, 10) nthroot(7, 0.5)
#include <stdio.h> #include <float.h> double pow_ (double x, int e) { int i; double r = 1; for (i = 0; i < e; i++) { r *= x; } return r; } double root (int n, double x) { double d, r = 1; if (!x) { return 0; } if (n < 1 || (x < 0 && !(n&1))) { return 0.0 / 0.0; } do { d = (x / pow_(r, n - 1) - r) / n; r += d; } while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10); return r; } int main () { int n = 15; double x = pow_(-3.14159, 15); printf("root(%d, %g) = %g\n", n, x, root(n, x)); return 0; }
Generate a C# translation of this R snippet without changing its computational steps.
nthroot <- function(A, n, tol=sqrt(.Machine$double.eps)) { ifelse(A < 1, x0 <- A * n, x0 <- A / n) repeat { x1 <- ((n-1)*x0 + A / x0^(n-1))/n if(abs(x1 - x0) > tol) x0 <- x1 else break } x1 } nthroot(7131.5^10, 10) nthroot(7, 0.5)
static void Main(string[] args) { Console.WriteLine(NthRoot(81,2,.001)); Console.WriteLine(NthRoot(1000,3,.001)); Console.ReadLine(); } public static double NthRoot(double A,int n, double p) { double _n= (double) n; double[] x = new double[2]; x[0] = A; x[1] = A/_n; while(Math.Abs(x[0] -x[1] ) > p) { x[1] = x[0]; x[0] = (1/_n)*(((_n-1)*x[1]) + (A/Math.Pow(x[1],_n-1))); } return x[0]; }
Preserve the algorithm and functionality while converting the code from R to C++.
nthroot <- function(A, n, tol=sqrt(.Machine$double.eps)) { ifelse(A < 1, x0 <- A * n, x0 <- A / n) repeat { x1 <- ((n-1)*x0 + A / x0^(n-1))/n if(abs(x1 - x0) > tol) x0 <- x1 else break } x1 } nthroot(7131.5^10, 10) nthroot(7, 0.5)
double NthRoot(double m_nValue, double index, double guess, double pc) { double result = guess; double result_next; do { result_next = (1.0/index)*((index-1.0)*result+(m_nValue)/(pow(result,(index-1.0)))); result = result_next; pc--; }while(pc>1); return result; };
Produce a functionally identical Java code for the snippet given in R.
nthroot <- function(A, n, tol=sqrt(.Machine$double.eps)) { ifelse(A < 1, x0 <- A * n, x0 <- A / n) repeat { x1 <- ((n-1)*x0 + A / x0^(n-1))/n if(abs(x1 - x0) > tol) x0 <- x1 else break } x1 } nthroot(7131.5^10, 10) nthroot(7, 0.5)
public static double nthroot(int n, double A) { return nthroot(n, A, .001); } public static double nthroot(int n, double A, double p) { if(A < 0) { System.err.println("A < 0"); return -1; } else if(A == 0) { return 0; } double x_prev = A; double x = A / n; while(Math.abs(x - x_prev) > p) { x_prev = x; x = ((n - 1.0) * x + A / Math.pow(x, n - 1.0)) / n; } return x; }
Rewrite the snippet below in Python so it works the same as the original R code.
nthroot <- function(A, n, tol=sqrt(.Machine$double.eps)) { ifelse(A < 1, x0 <- A * n, x0 <- A / n) repeat { x1 <- ((n-1)*x0 + A / x0^(n-1))/n if(abs(x1 - x0) > tol) x0 <- x1 else break } x1 } nthroot(7131.5^10, 10) nthroot(7, 0.5)
from decimal import Decimal, getcontext def nthroot (n, A, precision): getcontext().prec = precision n = Decimal(n) x_0 = A / n x_1 = 1 while True: x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1)))) if x_0 == x_1: return x_1
Convert this R block to VB, preserving its control flow and logic.
nthroot <- function(A, n, tol=sqrt(.Machine$double.eps)) { ifelse(A < 1, x0 <- A * n, x0 <- A / n) repeat { x1 <- ((n-1)*x0 + A / x0^(n-1))/n if(abs(x1 - x0) > tol) x0 <- x1 else break } x1 } nthroot(7131.5^10, 10) nthroot(7, 0.5)
Private Function nth_root(y As Double, n As Double) Dim eps As Double: eps = 0.00000000000001 Dim x As Variant: x = 1 Do While True d = (y / x ^ (n - 1) - x) / n x = x + d e = eps * x If d > -e And d < e Then Exit Do End If Loop Debug.Print y; n; x; y ^ (1 / n) End Function Public Sub main() nth_root 1024, 10 nth_root 27, 3 nth_root 2, 2 nth_root 5642, 125 nth_root 7, 0.5 nth_root 4913, 3 nth_root 8, 3 nth_root 16, 2 nth_root 16, 4 nth_root 125, 3 nth_root 1000000000, 3 nth_root 1000000000, 9 End Sub
Generate an equivalent Go version of this R code.
nthroot <- function(A, n, tol=sqrt(.Machine$double.eps)) { ifelse(A < 1, x0 <- A * n, x0 <- A / n) repeat { x1 <- ((n-1)*x0 + A / x0^(n-1))/n if(abs(x1 - x0) > tol) x0 <- x1 else break } x1 } nthroot(7131.5^10, 10) nthroot(7, 0.5)
func root(a float64, n int) float64 { n1 := n - 1 n1f, rn := float64(n1), 1/float64(n) x, x0 := 1., 0. for { potx, t2 := 1/x, a for b := n1; b > 0; b >>= 1 { if b&1 == 1 { t2 *= potx } potx *= potx } x0, x = x, rn*(n1f*x+t2) if math.Abs(x-x0)*1e15 < x { break } } return x }
Port the provided Racket code into C while preserving the original functionality.
#lang racket (define (nth-root number root (tolerance 0.001)) (define (acceptable? next current) (< (abs (- next current)) tolerance)) (define (improve current) (/ (+ (* (- root 1) current) (/ number (expt current (- root 1)))) root)) (define (loop current) (define next-guess (improve current)) (if (acceptable? next-guess current) next-guess (loop next-guess))) (loop 1.0))
#include <stdio.h> #include <float.h> double pow_ (double x, int e) { int i; double r = 1; for (i = 0; i < e; i++) { r *= x; } return r; } double root (int n, double x) { double d, r = 1; if (!x) { return 0; } if (n < 1 || (x < 0 && !(n&1))) { return 0.0 / 0.0; } do { d = (x / pow_(r, n - 1) - r) / n; r += d; } while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10); return r; } int main () { int n = 15; double x = pow_(-3.14159, 15); printf("root(%d, %g) = %g\n", n, x, root(n, x)); return 0; }
Change the following Racket code into C# without altering its purpose.
#lang racket (define (nth-root number root (tolerance 0.001)) (define (acceptable? next current) (< (abs (- next current)) tolerance)) (define (improve current) (/ (+ (* (- root 1) current) (/ number (expt current (- root 1)))) root)) (define (loop current) (define next-guess (improve current)) (if (acceptable? next-guess current) next-guess (loop next-guess))) (loop 1.0))
static void Main(string[] args) { Console.WriteLine(NthRoot(81,2,.001)); Console.WriteLine(NthRoot(1000,3,.001)); Console.ReadLine(); } public static double NthRoot(double A,int n, double p) { double _n= (double) n; double[] x = new double[2]; x[0] = A; x[1] = A/_n; while(Math.Abs(x[0] -x[1] ) > p) { x[1] = x[0]; x[0] = (1/_n)*(((_n-1)*x[1]) + (A/Math.Pow(x[1],_n-1))); } return x[0]; }
Convert the following code from Racket to C++, ensuring the logic remains intact.
#lang racket (define (nth-root number root (tolerance 0.001)) (define (acceptable? next current) (< (abs (- next current)) tolerance)) (define (improve current) (/ (+ (* (- root 1) current) (/ number (expt current (- root 1)))) root)) (define (loop current) (define next-guess (improve current)) (if (acceptable? next-guess current) next-guess (loop next-guess))) (loop 1.0))
double NthRoot(double m_nValue, double index, double guess, double pc) { double result = guess; double result_next; do { result_next = (1.0/index)*((index-1.0)*result+(m_nValue)/(pow(result,(index-1.0)))); result = result_next; pc--; }while(pc>1); return result; };
Generate a Java translation of this Racket snippet without changing its computational steps.
#lang racket (define (nth-root number root (tolerance 0.001)) (define (acceptable? next current) (< (abs (- next current)) tolerance)) (define (improve current) (/ (+ (* (- root 1) current) (/ number (expt current (- root 1)))) root)) (define (loop current) (define next-guess (improve current)) (if (acceptable? next-guess current) next-guess (loop next-guess))) (loop 1.0))
public static double nthroot(int n, double A) { return nthroot(n, A, .001); } public static double nthroot(int n, double A, double p) { if(A < 0) { System.err.println("A < 0"); return -1; } else if(A == 0) { return 0; } double x_prev = A; double x = A / n; while(Math.abs(x - x_prev) > p) { x_prev = x; x = ((n - 1.0) * x + A / Math.pow(x, n - 1.0)) / n; } return x; }
Port the provided Racket code into Python while preserving the original functionality.
#lang racket (define (nth-root number root (tolerance 0.001)) (define (acceptable? next current) (< (abs (- next current)) tolerance)) (define (improve current) (/ (+ (* (- root 1) current) (/ number (expt current (- root 1)))) root)) (define (loop current) (define next-guess (improve current)) (if (acceptable? next-guess current) next-guess (loop next-guess))) (loop 1.0))
from decimal import Decimal, getcontext def nthroot (n, A, precision): getcontext().prec = precision n = Decimal(n) x_0 = A / n x_1 = 1 while True: x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1)))) if x_0 == x_1: return x_1
Port the provided Racket code into VB while preserving the original functionality.
#lang racket (define (nth-root number root (tolerance 0.001)) (define (acceptable? next current) (< (abs (- next current)) tolerance)) (define (improve current) (/ (+ (* (- root 1) current) (/ number (expt current (- root 1)))) root)) (define (loop current) (define next-guess (improve current)) (if (acceptable? next-guess current) next-guess (loop next-guess))) (loop 1.0))
Private Function nth_root(y As Double, n As Double) Dim eps As Double: eps = 0.00000000000001 Dim x As Variant: x = 1 Do While True d = (y / x ^ (n - 1) - x) / n x = x + d e = eps * x If d > -e And d < e Then Exit Do End If Loop Debug.Print y; n; x; y ^ (1 / n) End Function Public Sub main() nth_root 1024, 10 nth_root 27, 3 nth_root 2, 2 nth_root 5642, 125 nth_root 7, 0.5 nth_root 4913, 3 nth_root 8, 3 nth_root 16, 2 nth_root 16, 4 nth_root 125, 3 nth_root 1000000000, 3 nth_root 1000000000, 9 End Sub
Produce a language-to-language conversion: from Racket to Go, same semantics.
#lang racket (define (nth-root number root (tolerance 0.001)) (define (acceptable? next current) (< (abs (- next current)) tolerance)) (define (improve current) (/ (+ (* (- root 1) current) (/ number (expt current (- root 1)))) root)) (define (loop current) (define next-guess (improve current)) (if (acceptable? next-guess current) next-guess (loop next-guess))) (loop 1.0))
func root(a float64, n int) float64 { n1 := n - 1 n1f, rn := float64(n1), 1/float64(n) x, x0 := 1., 0. for { potx, t2 := 1/x, a for b := n1; b > 0; b >>= 1 { if b&1 == 1 { t2 *= potx } potx *= potx } x0, x = x, rn*(n1f*x+t2) if math.Abs(x-x0)*1e15 < x { break } } return x }
Port the provided COBOL code into C while preserving the original functionality.
IDENTIFICATION DIVISION. PROGRAM-ID. Nth-Root. AUTHOR. Bill Gunshannon. INSTALLATION. DATE-WRITTEN. 4 Feb 2020. ************************************************************ ** Program Abstract: ** Compute the Nth Root of a positive real number. ** ** Takes values from console. If Precision is left ** blank defaults to 0.001. ** ** Enter 0 for first value to terminate program. ************************************************************ ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT Root-File ASSIGN TO "Root-File" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD Root-File DATA RECORD IS Parameters. 01 Parameters. 05 Root PIC 9(5). 05 Num PIC 9(5)V9(5). 05 Precision PIC 9V9(9). WORKING-STORAGE SECTION. 01 TEMP0 PIC 9(9)V9(9). 01 TEMP1 PIC 9(9)V9(9). 01 RESULTS. 05 Field1 PIC ZZZZZ.ZZZZZ. 05 FILLER PIC X(5). 05 Field2 PIC ZZZZ9. 05 FILLER PIC X(14). 05 Field3 PIC 9.999999999. 01 HEADER. 05 FILLER PIC X(72) VALUE " Number Root Precision.". 01 Disp-Root PIC ZZZZZ.ZZZZZ. PROCEDURE DIVISION. Main-Program. PERFORM FOREVER PERFORM Get-Input IF Precision = 0.0 THEN MOVE 0.001 to Precision END-IF PERFORM Compute-Root MOVE Root TO Field2 MOVE Num TO Field1 MOVE Precision TO Field3 DISPLAY HEADER DISPLAY RESULTS DISPLAY " " MOVE TEMP1 TO Disp-Root DISPLAY "The Root is: " Disp-Root END-PERFORM. Get-Input. DISPLAY "Input Base Number: " WITH NO ADVANCING ACCEPT Num IF Num EQUALS ZERO THEN DISPLAY "Good Bye." STOP RUN END-IF DISPLAY "Input Root: " WITH NO ADVANCING ACCEPT Root DISPLAY "Input Desired Precision: " WITH NO ADVANCING ACCEPT Precision. Compute-Root. MOVE Root TO TEMP0 DIVIDE Num BY Root GIVING TEMP1 PERFORM UNTIL FUNCTION ABS(TEMP0 - TEMP1) LESS THAN Precision MOVE TEMP1 TO TEMP0 COMPUTE TEMP1 = (( Root - 1.0) * TEMP1 + Num / TEMP1 ** (Root - 1.0)) / Root END-PERFORM. END-PROGRAM.
#include <stdio.h> #include <float.h> double pow_ (double x, int e) { int i; double r = 1; for (i = 0; i < e; i++) { r *= x; } return r; } double root (int n, double x) { double d, r = 1; if (!x) { return 0; } if (n < 1 || (x < 0 && !(n&1))) { return 0.0 / 0.0; } do { d = (x / pow_(r, n - 1) - r) / n; r += d; } while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10); return r; } int main () { int n = 15; double x = pow_(-3.14159, 15); printf("root(%d, %g) = %g\n", n, x, root(n, x)); return 0; }
Preserve the algorithm and functionality while converting the code from COBOL to C#.
IDENTIFICATION DIVISION. PROGRAM-ID. Nth-Root. AUTHOR. Bill Gunshannon. INSTALLATION. DATE-WRITTEN. 4 Feb 2020. ************************************************************ ** Program Abstract: ** Compute the Nth Root of a positive real number. ** ** Takes values from console. If Precision is left ** blank defaults to 0.001. ** ** Enter 0 for first value to terminate program. ************************************************************ ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT Root-File ASSIGN TO "Root-File" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD Root-File DATA RECORD IS Parameters. 01 Parameters. 05 Root PIC 9(5). 05 Num PIC 9(5)V9(5). 05 Precision PIC 9V9(9). WORKING-STORAGE SECTION. 01 TEMP0 PIC 9(9)V9(9). 01 TEMP1 PIC 9(9)V9(9). 01 RESULTS. 05 Field1 PIC ZZZZZ.ZZZZZ. 05 FILLER PIC X(5). 05 Field2 PIC ZZZZ9. 05 FILLER PIC X(14). 05 Field3 PIC 9.999999999. 01 HEADER. 05 FILLER PIC X(72) VALUE " Number Root Precision.". 01 Disp-Root PIC ZZZZZ.ZZZZZ. PROCEDURE DIVISION. Main-Program. PERFORM FOREVER PERFORM Get-Input IF Precision = 0.0 THEN MOVE 0.001 to Precision END-IF PERFORM Compute-Root MOVE Root TO Field2 MOVE Num TO Field1 MOVE Precision TO Field3 DISPLAY HEADER DISPLAY RESULTS DISPLAY " " MOVE TEMP1 TO Disp-Root DISPLAY "The Root is: " Disp-Root END-PERFORM. Get-Input. DISPLAY "Input Base Number: " WITH NO ADVANCING ACCEPT Num IF Num EQUALS ZERO THEN DISPLAY "Good Bye." STOP RUN END-IF DISPLAY "Input Root: " WITH NO ADVANCING ACCEPT Root DISPLAY "Input Desired Precision: " WITH NO ADVANCING ACCEPT Precision. Compute-Root. MOVE Root TO TEMP0 DIVIDE Num BY Root GIVING TEMP1 PERFORM UNTIL FUNCTION ABS(TEMP0 - TEMP1) LESS THAN Precision MOVE TEMP1 TO TEMP0 COMPUTE TEMP1 = (( Root - 1.0) * TEMP1 + Num / TEMP1 ** (Root - 1.0)) / Root END-PERFORM. END-PROGRAM.
static void Main(string[] args) { Console.WriteLine(NthRoot(81,2,.001)); Console.WriteLine(NthRoot(1000,3,.001)); Console.ReadLine(); } public static double NthRoot(double A,int n, double p) { double _n= (double) n; double[] x = new double[2]; x[0] = A; x[1] = A/_n; while(Math.Abs(x[0] -x[1] ) > p) { x[1] = x[0]; x[0] = (1/_n)*(((_n-1)*x[1]) + (A/Math.Pow(x[1],_n-1))); } return x[0]; }
Please provide an equivalent version of this COBOL code in C++.
IDENTIFICATION DIVISION. PROGRAM-ID. Nth-Root. AUTHOR. Bill Gunshannon. INSTALLATION. DATE-WRITTEN. 4 Feb 2020. ************************************************************ ** Program Abstract: ** Compute the Nth Root of a positive real number. ** ** Takes values from console. If Precision is left ** blank defaults to 0.001. ** ** Enter 0 for first value to terminate program. ************************************************************ ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT Root-File ASSIGN TO "Root-File" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD Root-File DATA RECORD IS Parameters. 01 Parameters. 05 Root PIC 9(5). 05 Num PIC 9(5)V9(5). 05 Precision PIC 9V9(9). WORKING-STORAGE SECTION. 01 TEMP0 PIC 9(9)V9(9). 01 TEMP1 PIC 9(9)V9(9). 01 RESULTS. 05 Field1 PIC ZZZZZ.ZZZZZ. 05 FILLER PIC X(5). 05 Field2 PIC ZZZZ9. 05 FILLER PIC X(14). 05 Field3 PIC 9.999999999. 01 HEADER. 05 FILLER PIC X(72) VALUE " Number Root Precision.". 01 Disp-Root PIC ZZZZZ.ZZZZZ. PROCEDURE DIVISION. Main-Program. PERFORM FOREVER PERFORM Get-Input IF Precision = 0.0 THEN MOVE 0.001 to Precision END-IF PERFORM Compute-Root MOVE Root TO Field2 MOVE Num TO Field1 MOVE Precision TO Field3 DISPLAY HEADER DISPLAY RESULTS DISPLAY " " MOVE TEMP1 TO Disp-Root DISPLAY "The Root is: " Disp-Root END-PERFORM. Get-Input. DISPLAY "Input Base Number: " WITH NO ADVANCING ACCEPT Num IF Num EQUALS ZERO THEN DISPLAY "Good Bye." STOP RUN END-IF DISPLAY "Input Root: " WITH NO ADVANCING ACCEPT Root DISPLAY "Input Desired Precision: " WITH NO ADVANCING ACCEPT Precision. Compute-Root. MOVE Root TO TEMP0 DIVIDE Num BY Root GIVING TEMP1 PERFORM UNTIL FUNCTION ABS(TEMP0 - TEMP1) LESS THAN Precision MOVE TEMP1 TO TEMP0 COMPUTE TEMP1 = (( Root - 1.0) * TEMP1 + Num / TEMP1 ** (Root - 1.0)) / Root END-PERFORM. END-PROGRAM.
double NthRoot(double m_nValue, double index, double guess, double pc) { double result = guess; double result_next; do { result_next = (1.0/index)*((index-1.0)*result+(m_nValue)/(pow(result,(index-1.0)))); result = result_next; pc--; }while(pc>1); return result; };
Rewrite this program in Java while keeping its functionality equivalent to the COBOL version.
IDENTIFICATION DIVISION. PROGRAM-ID. Nth-Root. AUTHOR. Bill Gunshannon. INSTALLATION. DATE-WRITTEN. 4 Feb 2020. ************************************************************ ** Program Abstract: ** Compute the Nth Root of a positive real number. ** ** Takes values from console. If Precision is left ** blank defaults to 0.001. ** ** Enter 0 for first value to terminate program. ************************************************************ ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT Root-File ASSIGN TO "Root-File" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD Root-File DATA RECORD IS Parameters. 01 Parameters. 05 Root PIC 9(5). 05 Num PIC 9(5)V9(5). 05 Precision PIC 9V9(9). WORKING-STORAGE SECTION. 01 TEMP0 PIC 9(9)V9(9). 01 TEMP1 PIC 9(9)V9(9). 01 RESULTS. 05 Field1 PIC ZZZZZ.ZZZZZ. 05 FILLER PIC X(5). 05 Field2 PIC ZZZZ9. 05 FILLER PIC X(14). 05 Field3 PIC 9.999999999. 01 HEADER. 05 FILLER PIC X(72) VALUE " Number Root Precision.". 01 Disp-Root PIC ZZZZZ.ZZZZZ. PROCEDURE DIVISION. Main-Program. PERFORM FOREVER PERFORM Get-Input IF Precision = 0.0 THEN MOVE 0.001 to Precision END-IF PERFORM Compute-Root MOVE Root TO Field2 MOVE Num TO Field1 MOVE Precision TO Field3 DISPLAY HEADER DISPLAY RESULTS DISPLAY " " MOVE TEMP1 TO Disp-Root DISPLAY "The Root is: " Disp-Root END-PERFORM. Get-Input. DISPLAY "Input Base Number: " WITH NO ADVANCING ACCEPT Num IF Num EQUALS ZERO THEN DISPLAY "Good Bye." STOP RUN END-IF DISPLAY "Input Root: " WITH NO ADVANCING ACCEPT Root DISPLAY "Input Desired Precision: " WITH NO ADVANCING ACCEPT Precision. Compute-Root. MOVE Root TO TEMP0 DIVIDE Num BY Root GIVING TEMP1 PERFORM UNTIL FUNCTION ABS(TEMP0 - TEMP1) LESS THAN Precision MOVE TEMP1 TO TEMP0 COMPUTE TEMP1 = (( Root - 1.0) * TEMP1 + Num / TEMP1 ** (Root - 1.0)) / Root END-PERFORM. END-PROGRAM.
public static double nthroot(int n, double A) { return nthroot(n, A, .001); } public static double nthroot(int n, double A, double p) { if(A < 0) { System.err.println("A < 0"); return -1; } else if(A == 0) { return 0; } double x_prev = A; double x = A / n; while(Math.abs(x - x_prev) > p) { x_prev = x; x = ((n - 1.0) * x + A / Math.pow(x, n - 1.0)) / n; } return x; }
Can you help me rewrite this code in Python instead of COBOL, keeping it the same logically?
IDENTIFICATION DIVISION. PROGRAM-ID. Nth-Root. AUTHOR. Bill Gunshannon. INSTALLATION. DATE-WRITTEN. 4 Feb 2020. ************************************************************ ** Program Abstract: ** Compute the Nth Root of a positive real number. ** ** Takes values from console. If Precision is left ** blank defaults to 0.001. ** ** Enter 0 for first value to terminate program. ************************************************************ ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT Root-File ASSIGN TO "Root-File" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD Root-File DATA RECORD IS Parameters. 01 Parameters. 05 Root PIC 9(5). 05 Num PIC 9(5)V9(5). 05 Precision PIC 9V9(9). WORKING-STORAGE SECTION. 01 TEMP0 PIC 9(9)V9(9). 01 TEMP1 PIC 9(9)V9(9). 01 RESULTS. 05 Field1 PIC ZZZZZ.ZZZZZ. 05 FILLER PIC X(5). 05 Field2 PIC ZZZZ9. 05 FILLER PIC X(14). 05 Field3 PIC 9.999999999. 01 HEADER. 05 FILLER PIC X(72) VALUE " Number Root Precision.". 01 Disp-Root PIC ZZZZZ.ZZZZZ. PROCEDURE DIVISION. Main-Program. PERFORM FOREVER PERFORM Get-Input IF Precision = 0.0 THEN MOVE 0.001 to Precision END-IF PERFORM Compute-Root MOVE Root TO Field2 MOVE Num TO Field1 MOVE Precision TO Field3 DISPLAY HEADER DISPLAY RESULTS DISPLAY " " MOVE TEMP1 TO Disp-Root DISPLAY "The Root is: " Disp-Root END-PERFORM. Get-Input. DISPLAY "Input Base Number: " WITH NO ADVANCING ACCEPT Num IF Num EQUALS ZERO THEN DISPLAY "Good Bye." STOP RUN END-IF DISPLAY "Input Root: " WITH NO ADVANCING ACCEPT Root DISPLAY "Input Desired Precision: " WITH NO ADVANCING ACCEPT Precision. Compute-Root. MOVE Root TO TEMP0 DIVIDE Num BY Root GIVING TEMP1 PERFORM UNTIL FUNCTION ABS(TEMP0 - TEMP1) LESS THAN Precision MOVE TEMP1 TO TEMP0 COMPUTE TEMP1 = (( Root - 1.0) * TEMP1 + Num / TEMP1 ** (Root - 1.0)) / Root END-PERFORM. END-PROGRAM.
from decimal import Decimal, getcontext def nthroot (n, A, precision): getcontext().prec = precision n = Decimal(n) x_0 = A / n x_1 = 1 while True: x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1)))) if x_0 == x_1: return x_1
Generate a VB translation of this COBOL snippet without changing its computational steps.
IDENTIFICATION DIVISION. PROGRAM-ID. Nth-Root. AUTHOR. Bill Gunshannon. INSTALLATION. DATE-WRITTEN. 4 Feb 2020. ************************************************************ ** Program Abstract: ** Compute the Nth Root of a positive real number. ** ** Takes values from console. If Precision is left ** blank defaults to 0.001. ** ** Enter 0 for first value to terminate program. ************************************************************ ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT Root-File ASSIGN TO "Root-File" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD Root-File DATA RECORD IS Parameters. 01 Parameters. 05 Root PIC 9(5). 05 Num PIC 9(5)V9(5). 05 Precision PIC 9V9(9). WORKING-STORAGE SECTION. 01 TEMP0 PIC 9(9)V9(9). 01 TEMP1 PIC 9(9)V9(9). 01 RESULTS. 05 Field1 PIC ZZZZZ.ZZZZZ. 05 FILLER PIC X(5). 05 Field2 PIC ZZZZ9. 05 FILLER PIC X(14). 05 Field3 PIC 9.999999999. 01 HEADER. 05 FILLER PIC X(72) VALUE " Number Root Precision.". 01 Disp-Root PIC ZZZZZ.ZZZZZ. PROCEDURE DIVISION. Main-Program. PERFORM FOREVER PERFORM Get-Input IF Precision = 0.0 THEN MOVE 0.001 to Precision END-IF PERFORM Compute-Root MOVE Root TO Field2 MOVE Num TO Field1 MOVE Precision TO Field3 DISPLAY HEADER DISPLAY RESULTS DISPLAY " " MOVE TEMP1 TO Disp-Root DISPLAY "The Root is: " Disp-Root END-PERFORM. Get-Input. DISPLAY "Input Base Number: " WITH NO ADVANCING ACCEPT Num IF Num EQUALS ZERO THEN DISPLAY "Good Bye." STOP RUN END-IF DISPLAY "Input Root: " WITH NO ADVANCING ACCEPT Root DISPLAY "Input Desired Precision: " WITH NO ADVANCING ACCEPT Precision. Compute-Root. MOVE Root TO TEMP0 DIVIDE Num BY Root GIVING TEMP1 PERFORM UNTIL FUNCTION ABS(TEMP0 - TEMP1) LESS THAN Precision MOVE TEMP1 TO TEMP0 COMPUTE TEMP1 = (( Root - 1.0) * TEMP1 + Num / TEMP1 ** (Root - 1.0)) / Root END-PERFORM. END-PROGRAM.
Private Function nth_root(y As Double, n As Double) Dim eps As Double: eps = 0.00000000000001 Dim x As Variant: x = 1 Do While True d = (y / x ^ (n - 1) - x) / n x = x + d e = eps * x If d > -e And d < e Then Exit Do End If Loop Debug.Print y; n; x; y ^ (1 / n) End Function Public Sub main() nth_root 1024, 10 nth_root 27, 3 nth_root 2, 2 nth_root 5642, 125 nth_root 7, 0.5 nth_root 4913, 3 nth_root 8, 3 nth_root 16, 2 nth_root 16, 4 nth_root 125, 3 nth_root 1000000000, 3 nth_root 1000000000, 9 End Sub
Rewrite the snippet below in Go so it works the same as the original COBOL code.
IDENTIFICATION DIVISION. PROGRAM-ID. Nth-Root. AUTHOR. Bill Gunshannon. INSTALLATION. DATE-WRITTEN. 4 Feb 2020. ************************************************************ ** Program Abstract: ** Compute the Nth Root of a positive real number. ** ** Takes values from console. If Precision is left ** blank defaults to 0.001. ** ** Enter 0 for first value to terminate program. ************************************************************ ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT Root-File ASSIGN TO "Root-File" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD Root-File DATA RECORD IS Parameters. 01 Parameters. 05 Root PIC 9(5). 05 Num PIC 9(5)V9(5). 05 Precision PIC 9V9(9). WORKING-STORAGE SECTION. 01 TEMP0 PIC 9(9)V9(9). 01 TEMP1 PIC 9(9)V9(9). 01 RESULTS. 05 Field1 PIC ZZZZZ.ZZZZZ. 05 FILLER PIC X(5). 05 Field2 PIC ZZZZ9. 05 FILLER PIC X(14). 05 Field3 PIC 9.999999999. 01 HEADER. 05 FILLER PIC X(72) VALUE " Number Root Precision.". 01 Disp-Root PIC ZZZZZ.ZZZZZ. PROCEDURE DIVISION. Main-Program. PERFORM FOREVER PERFORM Get-Input IF Precision = 0.0 THEN MOVE 0.001 to Precision END-IF PERFORM Compute-Root MOVE Root TO Field2 MOVE Num TO Field1 MOVE Precision TO Field3 DISPLAY HEADER DISPLAY RESULTS DISPLAY " " MOVE TEMP1 TO Disp-Root DISPLAY "The Root is: " Disp-Root END-PERFORM. Get-Input. DISPLAY "Input Base Number: " WITH NO ADVANCING ACCEPT Num IF Num EQUALS ZERO THEN DISPLAY "Good Bye." STOP RUN END-IF DISPLAY "Input Root: " WITH NO ADVANCING ACCEPT Root DISPLAY "Input Desired Precision: " WITH NO ADVANCING ACCEPT Precision. Compute-Root. MOVE Root TO TEMP0 DIVIDE Num BY Root GIVING TEMP1 PERFORM UNTIL FUNCTION ABS(TEMP0 - TEMP1) LESS THAN Precision MOVE TEMP1 TO TEMP0 COMPUTE TEMP1 = (( Root - 1.0) * TEMP1 + Num / TEMP1 ** (Root - 1.0)) / Root END-PERFORM. END-PROGRAM.
func root(a float64, n int) float64 { n1 := n - 1 n1f, rn := float64(n1), 1/float64(n) x, x0 := 1., 0. for { potx, t2 := 1/x, a for b := n1; b > 0; b >>= 1 { if b&1 == 1 { t2 *= potx } potx *= potx } x0, x = x, rn*(n1f*x+t2) if math.Abs(x-x0)*1e15 < x { break } } return x }
Change the programming language of this snippet from REXX to C without modifying what it does.
class nth_root method main(args=String[]) static if args.length < 2 then do say "at least 2 arguments expected" exit end x = args[0] root = args[1] if args.length > 2 then digs = args[2] if root=='' then root=2 if digs = null, digs = '' then digs=20 numeric digits digs say ' x = ' x say ' root = ' root say 'digits = ' digs say 'answer = ' root(x,root,digs) method root(x,r,digs) static --procedure; parse arg x,R 1 oldR R = r oldR = r if r=0 then do say say '*** error! ***' say "a root of zero can't be specified." say return '[n/a]' end R=R.abs() if x<0 & (R//2==0) then do say say '*** error! ***' say "an even root can't be calculated for a" - 'negative number,' say 'the result would be complex.' say return '[n/a]' end if x=0 | r=1 then return x/1 Rm1=R-1 oldDigs=digs dm=oldDigs+5 ax=x.abs() g=(ax+1)/r**r -- numeric fuzz 3 d=5 loop forever d=d+d if d>dm then d = dm numeric digits d old=0 loop forever _=(Rm1*g**R+ax)/R/g**rm1 if _=g | _=old then leave old=g g=_ end if d==dm then leave end _=g*x.sign() if oldR<0 then return _=1/_ numeric digits oldDigs return _/1
#include <stdio.h> #include <float.h> double pow_ (double x, int e) { int i; double r = 1; for (i = 0; i < e; i++) { r *= x; } return r; } double root (int n, double x) { double d, r = 1; if (!x) { return 0; } if (n < 1 || (x < 0 && !(n&1))) { return 0.0 / 0.0; } do { d = (x / pow_(r, n - 1) - r) / n; r += d; } while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10); return r; } int main () { int n = 15; double x = pow_(-3.14159, 15); printf("root(%d, %g) = %g\n", n, x, root(n, x)); return 0; }
Write the same algorithm in C# as shown in this REXX implementation.
class nth_root method main(args=String[]) static if args.length < 2 then do say "at least 2 arguments expected" exit end x = args[0] root = args[1] if args.length > 2 then digs = args[2] if root=='' then root=2 if digs = null, digs = '' then digs=20 numeric digits digs say ' x = ' x say ' root = ' root say 'digits = ' digs say 'answer = ' root(x,root,digs) method root(x,r,digs) static --procedure; parse arg x,R 1 oldR R = r oldR = r if r=0 then do say say '*** error! ***' say "a root of zero can't be specified." say return '[n/a]' end R=R.abs() if x<0 & (R//2==0) then do say say '*** error! ***' say "an even root can't be calculated for a" - 'negative number,' say 'the result would be complex.' say return '[n/a]' end if x=0 | r=1 then return x/1 Rm1=R-1 oldDigs=digs dm=oldDigs+5 ax=x.abs() g=(ax+1)/r**r -- numeric fuzz 3 d=5 loop forever d=d+d if d>dm then d = dm numeric digits d old=0 loop forever _=(Rm1*g**R+ax)/R/g**rm1 if _=g | _=old then leave old=g g=_ end if d==dm then leave end _=g*x.sign() if oldR<0 then return _=1/_ numeric digits oldDigs return _/1
static void Main(string[] args) { Console.WriteLine(NthRoot(81,2,.001)); Console.WriteLine(NthRoot(1000,3,.001)); Console.ReadLine(); } public static double NthRoot(double A,int n, double p) { double _n= (double) n; double[] x = new double[2]; x[0] = A; x[1] = A/_n; while(Math.Abs(x[0] -x[1] ) > p) { x[1] = x[0]; x[0] = (1/_n)*(((_n-1)*x[1]) + (A/Math.Pow(x[1],_n-1))); } return x[0]; }
Port the provided REXX code into C++ while preserving the original functionality.
class nth_root method main(args=String[]) static if args.length < 2 then do say "at least 2 arguments expected" exit end x = args[0] root = args[1] if args.length > 2 then digs = args[2] if root=='' then root=2 if digs = null, digs = '' then digs=20 numeric digits digs say ' x = ' x say ' root = ' root say 'digits = ' digs say 'answer = ' root(x,root,digs) method root(x,r,digs) static --procedure; parse arg x,R 1 oldR R = r oldR = r if r=0 then do say say '*** error! ***' say "a root of zero can't be specified." say return '[n/a]' end R=R.abs() if x<0 & (R//2==0) then do say say '*** error! ***' say "an even root can't be calculated for a" - 'negative number,' say 'the result would be complex.' say return '[n/a]' end if x=0 | r=1 then return x/1 Rm1=R-1 oldDigs=digs dm=oldDigs+5 ax=x.abs() g=(ax+1)/r**r -- numeric fuzz 3 d=5 loop forever d=d+d if d>dm then d = dm numeric digits d old=0 loop forever _=(Rm1*g**R+ax)/R/g**rm1 if _=g | _=old then leave old=g g=_ end if d==dm then leave end _=g*x.sign() if oldR<0 then return _=1/_ numeric digits oldDigs return _/1
double NthRoot(double m_nValue, double index, double guess, double pc) { double result = guess; double result_next; do { result_next = (1.0/index)*((index-1.0)*result+(m_nValue)/(pow(result,(index-1.0)))); result = result_next; pc--; }while(pc>1); return result; };
Please provide an equivalent version of this REXX code in Java.
class nth_root method main(args=String[]) static if args.length < 2 then do say "at least 2 arguments expected" exit end x = args[0] root = args[1] if args.length > 2 then digs = args[2] if root=='' then root=2 if digs = null, digs = '' then digs=20 numeric digits digs say ' x = ' x say ' root = ' root say 'digits = ' digs say 'answer = ' root(x,root,digs) method root(x,r,digs) static --procedure; parse arg x,R 1 oldR R = r oldR = r if r=0 then do say say '*** error! ***' say "a root of zero can't be specified." say return '[n/a]' end R=R.abs() if x<0 & (R//2==0) then do say say '*** error! ***' say "an even root can't be calculated for a" - 'negative number,' say 'the result would be complex.' say return '[n/a]' end if x=0 | r=1 then return x/1 Rm1=R-1 oldDigs=digs dm=oldDigs+5 ax=x.abs() g=(ax+1)/r**r -- numeric fuzz 3 d=5 loop forever d=d+d if d>dm then d = dm numeric digits d old=0 loop forever _=(Rm1*g**R+ax)/R/g**rm1 if _=g | _=old then leave old=g g=_ end if d==dm then leave end _=g*x.sign() if oldR<0 then return _=1/_ numeric digits oldDigs return _/1
public static double nthroot(int n, double A) { return nthroot(n, A, .001); } public static double nthroot(int n, double A, double p) { if(A < 0) { System.err.println("A < 0"); return -1; } else if(A == 0) { return 0; } double x_prev = A; double x = A / n; while(Math.abs(x - x_prev) > p) { x_prev = x; x = ((n - 1.0) * x + A / Math.pow(x, n - 1.0)) / n; } return x; }
Keep all operations the same but rewrite the snippet in Python.
class nth_root method main(args=String[]) static if args.length < 2 then do say "at least 2 arguments expected" exit end x = args[0] root = args[1] if args.length > 2 then digs = args[2] if root=='' then root=2 if digs = null, digs = '' then digs=20 numeric digits digs say ' x = ' x say ' root = ' root say 'digits = ' digs say 'answer = ' root(x,root,digs) method root(x,r,digs) static --procedure; parse arg x,R 1 oldR R = r oldR = r if r=0 then do say say '*** error! ***' say "a root of zero can't be specified." say return '[n/a]' end R=R.abs() if x<0 & (R//2==0) then do say say '*** error! ***' say "an even root can't be calculated for a" - 'negative number,' say 'the result would be complex.' say return '[n/a]' end if x=0 | r=1 then return x/1 Rm1=R-1 oldDigs=digs dm=oldDigs+5 ax=x.abs() g=(ax+1)/r**r -- numeric fuzz 3 d=5 loop forever d=d+d if d>dm then d = dm numeric digits d old=0 loop forever _=(Rm1*g**R+ax)/R/g**rm1 if _=g | _=old then leave old=g g=_ end if d==dm then leave end _=g*x.sign() if oldR<0 then return _=1/_ numeric digits oldDigs return _/1
from decimal import Decimal, getcontext def nthroot (n, A, precision): getcontext().prec = precision n = Decimal(n) x_0 = A / n x_1 = 1 while True: x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1)))) if x_0 == x_1: return x_1
Port the provided REXX code into VB while preserving the original functionality.
class nth_root method main(args=String[]) static if args.length < 2 then do say "at least 2 arguments expected" exit end x = args[0] root = args[1] if args.length > 2 then digs = args[2] if root=='' then root=2 if digs = null, digs = '' then digs=20 numeric digits digs say ' x = ' x say ' root = ' root say 'digits = ' digs say 'answer = ' root(x,root,digs) method root(x,r,digs) static --procedure; parse arg x,R 1 oldR R = r oldR = r if r=0 then do say say '*** error! ***' say "a root of zero can't be specified." say return '[n/a]' end R=R.abs() if x<0 & (R//2==0) then do say say '*** error! ***' say "an even root can't be calculated for a" - 'negative number,' say 'the result would be complex.' say return '[n/a]' end if x=0 | r=1 then return x/1 Rm1=R-1 oldDigs=digs dm=oldDigs+5 ax=x.abs() g=(ax+1)/r**r -- numeric fuzz 3 d=5 loop forever d=d+d if d>dm then d = dm numeric digits d old=0 loop forever _=(Rm1*g**R+ax)/R/g**rm1 if _=g | _=old then leave old=g g=_ end if d==dm then leave end _=g*x.sign() if oldR<0 then return _=1/_ numeric digits oldDigs return _/1
Private Function nth_root(y As Double, n As Double) Dim eps As Double: eps = 0.00000000000001 Dim x As Variant: x = 1 Do While True d = (y / x ^ (n - 1) - x) / n x = x + d e = eps * x If d > -e And d < e Then Exit Do End If Loop Debug.Print y; n; x; y ^ (1 / n) End Function Public Sub main() nth_root 1024, 10 nth_root 27, 3 nth_root 2, 2 nth_root 5642, 125 nth_root 7, 0.5 nth_root 4913, 3 nth_root 8, 3 nth_root 16, 2 nth_root 16, 4 nth_root 125, 3 nth_root 1000000000, 3 nth_root 1000000000, 9 End Sub
Port the following code from REXX to Go with equivalent syntax and logic.
class nth_root method main(args=String[]) static if args.length < 2 then do say "at least 2 arguments expected" exit end x = args[0] root = args[1] if args.length > 2 then digs = args[2] if root=='' then root=2 if digs = null, digs = '' then digs=20 numeric digits digs say ' x = ' x say ' root = ' root say 'digits = ' digs say 'answer = ' root(x,root,digs) method root(x,r,digs) static --procedure; parse arg x,R 1 oldR R = r oldR = r if r=0 then do say say '*** error! ***' say "a root of zero can't be specified." say return '[n/a]' end R=R.abs() if x<0 & (R//2==0) then do say say '*** error! ***' say "an even root can't be calculated for a" - 'negative number,' say 'the result would be complex.' say return '[n/a]' end if x=0 | r=1 then return x/1 Rm1=R-1 oldDigs=digs dm=oldDigs+5 ax=x.abs() g=(ax+1)/r**r -- numeric fuzz 3 d=5 loop forever d=d+d if d>dm then d = dm numeric digits d old=0 loop forever _=(Rm1*g**R+ax)/R/g**rm1 if _=g | _=old then leave old=g g=_ end if d==dm then leave end _=g*x.sign() if oldR<0 then return _=1/_ numeric digits oldDigs return _/1
func root(a float64, n int) float64 { n1 := n - 1 n1f, rn := float64(n1), 1/float64(n) x, x0 := 1., 0. for { potx, t2 := 1/x, a for b := n1; b > 0; b >>= 1 { if b&1 == 1 { t2 *= potx } potx *= potx } x0, x = x, rn*(n1f*x+t2) if math.Abs(x-x0)*1e15 < x { break } } return x }
Change the programming language of this snippet from Ruby to C without modifying what it does.
def nthroot(n, a, precision = 1e-5) x = Float(a) begin prev = x x = ((n - 1) * prev + a / (prev ** (n - 1))) / n end while (prev - x).abs > precision x end p nthroot(5,34)
#include <stdio.h> #include <float.h> double pow_ (double x, int e) { int i; double r = 1; for (i = 0; i < e; i++) { r *= x; } return r; } double root (int n, double x) { double d, r = 1; if (!x) { return 0; } if (n < 1 || (x < 0 && !(n&1))) { return 0.0 / 0.0; } do { d = (x / pow_(r, n - 1) - r) / n; r += d; } while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10); return r; } int main () { int n = 15; double x = pow_(-3.14159, 15); printf("root(%d, %g) = %g\n", n, x, root(n, x)); return 0; }
Rewrite the snippet below in C# so it works the same as the original Ruby code.
def nthroot(n, a, precision = 1e-5) x = Float(a) begin prev = x x = ((n - 1) * prev + a / (prev ** (n - 1))) / n end while (prev - x).abs > precision x end p nthroot(5,34)
static void Main(string[] args) { Console.WriteLine(NthRoot(81,2,.001)); Console.WriteLine(NthRoot(1000,3,.001)); Console.ReadLine(); } public static double NthRoot(double A,int n, double p) { double _n= (double) n; double[] x = new double[2]; x[0] = A; x[1] = A/_n; while(Math.Abs(x[0] -x[1] ) > p) { x[1] = x[0]; x[0] = (1/_n)*(((_n-1)*x[1]) + (A/Math.Pow(x[1],_n-1))); } return x[0]; }
Change the programming language of this snippet from Ruby to C++ without modifying what it does.
def nthroot(n, a, precision = 1e-5) x = Float(a) begin prev = x x = ((n - 1) * prev + a / (prev ** (n - 1))) / n end while (prev - x).abs > precision x end p nthroot(5,34)
double NthRoot(double m_nValue, double index, double guess, double pc) { double result = guess; double result_next; do { result_next = (1.0/index)*((index-1.0)*result+(m_nValue)/(pow(result,(index-1.0)))); result = result_next; pc--; }while(pc>1); return result; };
Change the following Ruby code into Java without altering its purpose.
def nthroot(n, a, precision = 1e-5) x = Float(a) begin prev = x x = ((n - 1) * prev + a / (prev ** (n - 1))) / n end while (prev - x).abs > precision x end p nthroot(5,34)
public static double nthroot(int n, double A) { return nthroot(n, A, .001); } public static double nthroot(int n, double A, double p) { if(A < 0) { System.err.println("A < 0"); return -1; } else if(A == 0) { return 0; } double x_prev = A; double x = A / n; while(Math.abs(x - x_prev) > p) { x_prev = x; x = ((n - 1.0) * x + A / Math.pow(x, n - 1.0)) / n; } return x; }
Convert this Ruby snippet to Python and keep its semantics consistent.
def nthroot(n, a, precision = 1e-5) x = Float(a) begin prev = x x = ((n - 1) * prev + a / (prev ** (n - 1))) / n end while (prev - x).abs > precision x end p nthroot(5,34)
from decimal import Decimal, getcontext def nthroot (n, A, precision): getcontext().prec = precision n = Decimal(n) x_0 = A / n x_1 = 1 while True: x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1)))) if x_0 == x_1: return x_1
Write the same algorithm in VB as shown in this Ruby implementation.
def nthroot(n, a, precision = 1e-5) x = Float(a) begin prev = x x = ((n - 1) * prev + a / (prev ** (n - 1))) / n end while (prev - x).abs > precision x end p nthroot(5,34)
Private Function nth_root(y As Double, n As Double) Dim eps As Double: eps = 0.00000000000001 Dim x As Variant: x = 1 Do While True d = (y / x ^ (n - 1) - x) / n x = x + d e = eps * x If d > -e And d < e Then Exit Do End If Loop Debug.Print y; n; x; y ^ (1 / n) End Function Public Sub main() nth_root 1024, 10 nth_root 27, 3 nth_root 2, 2 nth_root 5642, 125 nth_root 7, 0.5 nth_root 4913, 3 nth_root 8, 3 nth_root 16, 2 nth_root 16, 4 nth_root 125, 3 nth_root 1000000000, 3 nth_root 1000000000, 9 End Sub
Rewrite the snippet below in Go so it works the same as the original Ruby code.
def nthroot(n, a, precision = 1e-5) x = Float(a) begin prev = x x = ((n - 1) * prev + a / (prev ** (n - 1))) / n end while (prev - x).abs > precision x end p nthroot(5,34)
func root(a float64, n int) float64 { n1 := n - 1 n1f, rn := float64(n1), 1/float64(n) x, x0 := 1., 0. for { potx, t2 := 1/x, a for b := n1; b > 0; b >>= 1 { if b&1 == 1 { t2 *= potx } potx *= potx } x0, x = x, rn*(n1f*x+t2) if math.Abs(x-x0)*1e15 < x { break } } return x }
Generate a C translation of this Scala snippet without changing its computational steps.
fun nthRoot(x: Double, n: Int): Double { if (n < 2) throw IllegalArgumentException("n must be more than 1") if (x <= 0.0) throw IllegalArgumentException("x must be positive") val np = n - 1 fun iter(g: Double) = (np * g + x / Math.pow(g, np.toDouble())) / n var g1 = x var g2 = iter(g1) while (g1 != g2) { g1 = iter(g1) g2 = iter(iter(g2)) } return g1 } fun main(args: Array<String>) { val numbers = arrayOf(1728.0 to 3, 1024.0 to 10, 2.0 to 2) for (number in numbers) println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}") }
#include <stdio.h> #include <float.h> double pow_ (double x, int e) { int i; double r = 1; for (i = 0; i < e; i++) { r *= x; } return r; } double root (int n, double x) { double d, r = 1; if (!x) { return 0; } if (n < 1 || (x < 0 && !(n&1))) { return 0.0 / 0.0; } do { d = (x / pow_(r, n - 1) - r) / n; r += d; } while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10); return r; } int main () { int n = 15; double x = pow_(-3.14159, 15); printf("root(%d, %g) = %g\n", n, x, root(n, x)); return 0; }
Write the same code in C# as shown below in Scala.
fun nthRoot(x: Double, n: Int): Double { if (n < 2) throw IllegalArgumentException("n must be more than 1") if (x <= 0.0) throw IllegalArgumentException("x must be positive") val np = n - 1 fun iter(g: Double) = (np * g + x / Math.pow(g, np.toDouble())) / n var g1 = x var g2 = iter(g1) while (g1 != g2) { g1 = iter(g1) g2 = iter(iter(g2)) } return g1 } fun main(args: Array<String>) { val numbers = arrayOf(1728.0 to 3, 1024.0 to 10, 2.0 to 2) for (number in numbers) println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}") }
static void Main(string[] args) { Console.WriteLine(NthRoot(81,2,.001)); Console.WriteLine(NthRoot(1000,3,.001)); Console.ReadLine(); } public static double NthRoot(double A,int n, double p) { double _n= (double) n; double[] x = new double[2]; x[0] = A; x[1] = A/_n; while(Math.Abs(x[0] -x[1] ) > p) { x[1] = x[0]; x[0] = (1/_n)*(((_n-1)*x[1]) + (A/Math.Pow(x[1],_n-1))); } return x[0]; }
Keep all operations the same but rewrite the snippet in C++.
fun nthRoot(x: Double, n: Int): Double { if (n < 2) throw IllegalArgumentException("n must be more than 1") if (x <= 0.0) throw IllegalArgumentException("x must be positive") val np = n - 1 fun iter(g: Double) = (np * g + x / Math.pow(g, np.toDouble())) / n var g1 = x var g2 = iter(g1) while (g1 != g2) { g1 = iter(g1) g2 = iter(iter(g2)) } return g1 } fun main(args: Array<String>) { val numbers = arrayOf(1728.0 to 3, 1024.0 to 10, 2.0 to 2) for (number in numbers) println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}") }
double NthRoot(double m_nValue, double index, double guess, double pc) { double result = guess; double result_next; do { result_next = (1.0/index)*((index-1.0)*result+(m_nValue)/(pow(result,(index-1.0)))); result = result_next; pc--; }while(pc>1); return result; };
Change the programming language of this snippet from Scala to Java without modifying what it does.
fun nthRoot(x: Double, n: Int): Double { if (n < 2) throw IllegalArgumentException("n must be more than 1") if (x <= 0.0) throw IllegalArgumentException("x must be positive") val np = n - 1 fun iter(g: Double) = (np * g + x / Math.pow(g, np.toDouble())) / n var g1 = x var g2 = iter(g1) while (g1 != g2) { g1 = iter(g1) g2 = iter(iter(g2)) } return g1 } fun main(args: Array<String>) { val numbers = arrayOf(1728.0 to 3, 1024.0 to 10, 2.0 to 2) for (number in numbers) println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}") }
public static double nthroot(int n, double A) { return nthroot(n, A, .001); } public static double nthroot(int n, double A, double p) { if(A < 0) { System.err.println("A < 0"); return -1; } else if(A == 0) { return 0; } double x_prev = A; double x = A / n; while(Math.abs(x - x_prev) > p) { x_prev = x; x = ((n - 1.0) * x + A / Math.pow(x, n - 1.0)) / n; } return x; }
Change the programming language of this snippet from Scala to Python without modifying what it does.
fun nthRoot(x: Double, n: Int): Double { if (n < 2) throw IllegalArgumentException("n must be more than 1") if (x <= 0.0) throw IllegalArgumentException("x must be positive") val np = n - 1 fun iter(g: Double) = (np * g + x / Math.pow(g, np.toDouble())) / n var g1 = x var g2 = iter(g1) while (g1 != g2) { g1 = iter(g1) g2 = iter(iter(g2)) } return g1 } fun main(args: Array<String>) { val numbers = arrayOf(1728.0 to 3, 1024.0 to 10, 2.0 to 2) for (number in numbers) println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}") }
from decimal import Decimal, getcontext def nthroot (n, A, precision): getcontext().prec = precision n = Decimal(n) x_0 = A / n x_1 = 1 while True: x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1)))) if x_0 == x_1: return x_1
Maintain the same structure and functionality when rewriting this code in VB.
fun nthRoot(x: Double, n: Int): Double { if (n < 2) throw IllegalArgumentException("n must be more than 1") if (x <= 0.0) throw IllegalArgumentException("x must be positive") val np = n - 1 fun iter(g: Double) = (np * g + x / Math.pow(g, np.toDouble())) / n var g1 = x var g2 = iter(g1) while (g1 != g2) { g1 = iter(g1) g2 = iter(iter(g2)) } return g1 } fun main(args: Array<String>) { val numbers = arrayOf(1728.0 to 3, 1024.0 to 10, 2.0 to 2) for (number in numbers) println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}") }
Private Function nth_root(y As Double, n As Double) Dim eps As Double: eps = 0.00000000000001 Dim x As Variant: x = 1 Do While True d = (y / x ^ (n - 1) - x) / n x = x + d e = eps * x If d > -e And d < e Then Exit Do End If Loop Debug.Print y; n; x; y ^ (1 / n) End Function Public Sub main() nth_root 1024, 10 nth_root 27, 3 nth_root 2, 2 nth_root 5642, 125 nth_root 7, 0.5 nth_root 4913, 3 nth_root 8, 3 nth_root 16, 2 nth_root 16, 4 nth_root 125, 3 nth_root 1000000000, 3 nth_root 1000000000, 9 End Sub
Ensure the translated Go code behaves exactly like the original Scala snippet.
fun nthRoot(x: Double, n: Int): Double { if (n < 2) throw IllegalArgumentException("n must be more than 1") if (x <= 0.0) throw IllegalArgumentException("x must be positive") val np = n - 1 fun iter(g: Double) = (np * g + x / Math.pow(g, np.toDouble())) / n var g1 = x var g2 = iter(g1) while (g1 != g2) { g1 = iter(g1) g2 = iter(iter(g2)) } return g1 } fun main(args: Array<String>) { val numbers = arrayOf(1728.0 to 3, 1024.0 to 10, 2.0 to 2) for (number in numbers) println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}") }
func root(a float64, n int) float64 { n1 := n - 1 n1f, rn := float64(n1), 1/float64(n) x, x0 := 1., 0. for { potx, t2 := 1/x, a for b := n1; b > 0; b >>= 1 { if b&1 == 1 { t2 *= potx } potx *= potx } x0, x = x, rn*(n1f*x+t2) if math.Abs(x-x0)*1e15 < x { break } } return x }
Produce a functionally identical C code for the snippet given in Swift.
extension FloatingPoint where Self: ExpressibleByFloatLiteral { @inlinable public func power(_ e: Int) -> Self { var res = Self(1) for _ in 0..<e { res *= self } return res } @inlinable public func root(n: Int, epsilon: Self = 2.220446049250313e-16) -> Self { var d = Self(0) var res = Self(1) guard self != 0 else { return 0 } guard n >= 1 else { return .nan } repeat { d = (self / res.power(n - 1) - res) / Self(n) res += d } while d >= epsilon * 10 || d <= -epsilon * 10 return res } } print(81.root(n: 4)) print(13.root(n: 5))
#include <stdio.h> #include <float.h> double pow_ (double x, int e) { int i; double r = 1; for (i = 0; i < e; i++) { r *= x; } return r; } double root (int n, double x) { double d, r = 1; if (!x) { return 0; } if (n < 1 || (x < 0 && !(n&1))) { return 0.0 / 0.0; } do { d = (x / pow_(r, n - 1) - r) / n; r += d; } while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10); return r; } int main () { int n = 15; double x = pow_(-3.14159, 15); printf("root(%d, %g) = %g\n", n, x, root(n, x)); return 0; }
Convert this Swift block to C#, preserving its control flow and logic.
extension FloatingPoint where Self: ExpressibleByFloatLiteral { @inlinable public func power(_ e: Int) -> Self { var res = Self(1) for _ in 0..<e { res *= self } return res } @inlinable public func root(n: Int, epsilon: Self = 2.220446049250313e-16) -> Self { var d = Self(0) var res = Self(1) guard self != 0 else { return 0 } guard n >= 1 else { return .nan } repeat { d = (self / res.power(n - 1) - res) / Self(n) res += d } while d >= epsilon * 10 || d <= -epsilon * 10 return res } } print(81.root(n: 4)) print(13.root(n: 5))
static void Main(string[] args) { Console.WriteLine(NthRoot(81,2,.001)); Console.WriteLine(NthRoot(1000,3,.001)); Console.ReadLine(); } public static double NthRoot(double A,int n, double p) { double _n= (double) n; double[] x = new double[2]; x[0] = A; x[1] = A/_n; while(Math.Abs(x[0] -x[1] ) > p) { x[1] = x[0]; x[0] = (1/_n)*(((_n-1)*x[1]) + (A/Math.Pow(x[1],_n-1))); } return x[0]; }
Produce a functionally identical C++ code for the snippet given in Swift.
extension FloatingPoint where Self: ExpressibleByFloatLiteral { @inlinable public func power(_ e: Int) -> Self { var res = Self(1) for _ in 0..<e { res *= self } return res } @inlinable public func root(n: Int, epsilon: Self = 2.220446049250313e-16) -> Self { var d = Self(0) var res = Self(1) guard self != 0 else { return 0 } guard n >= 1 else { return .nan } repeat { d = (self / res.power(n - 1) - res) / Self(n) res += d } while d >= epsilon * 10 || d <= -epsilon * 10 return res } } print(81.root(n: 4)) print(13.root(n: 5))
double NthRoot(double m_nValue, double index, double guess, double pc) { double result = guess; double result_next; do { result_next = (1.0/index)*((index-1.0)*result+(m_nValue)/(pow(result,(index-1.0)))); result = result_next; pc--; }while(pc>1); return result; };
Transform the following Swift implementation into Java, maintaining the same output and logic.
extension FloatingPoint where Self: ExpressibleByFloatLiteral { @inlinable public func power(_ e: Int) -> Self { var res = Self(1) for _ in 0..<e { res *= self } return res } @inlinable public func root(n: Int, epsilon: Self = 2.220446049250313e-16) -> Self { var d = Self(0) var res = Self(1) guard self != 0 else { return 0 } guard n >= 1 else { return .nan } repeat { d = (self / res.power(n - 1) - res) / Self(n) res += d } while d >= epsilon * 10 || d <= -epsilon * 10 return res } } print(81.root(n: 4)) print(13.root(n: 5))
public static double nthroot(int n, double A) { return nthroot(n, A, .001); } public static double nthroot(int n, double A, double p) { if(A < 0) { System.err.println("A < 0"); return -1; } else if(A == 0) { return 0; } double x_prev = A; double x = A / n; while(Math.abs(x - x_prev) > p) { x_prev = x; x = ((n - 1.0) * x + A / Math.pow(x, n - 1.0)) / n; } return x; }
Convert this Swift block to Python, preserving its control flow and logic.
extension FloatingPoint where Self: ExpressibleByFloatLiteral { @inlinable public func power(_ e: Int) -> Self { var res = Self(1) for _ in 0..<e { res *= self } return res } @inlinable public func root(n: Int, epsilon: Self = 2.220446049250313e-16) -> Self { var d = Self(0) var res = Self(1) guard self != 0 else { return 0 } guard n >= 1 else { return .nan } repeat { d = (self / res.power(n - 1) - res) / Self(n) res += d } while d >= epsilon * 10 || d <= -epsilon * 10 return res } } print(81.root(n: 4)) print(13.root(n: 5))
from decimal import Decimal, getcontext def nthroot (n, A, precision): getcontext().prec = precision n = Decimal(n) x_0 = A / n x_1 = 1 while True: x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1)))) if x_0 == x_1: return x_1
Produce a language-to-language conversion: from Swift to VB, same semantics.
extension FloatingPoint where Self: ExpressibleByFloatLiteral { @inlinable public func power(_ e: Int) -> Self { var res = Self(1) for _ in 0..<e { res *= self } return res } @inlinable public func root(n: Int, epsilon: Self = 2.220446049250313e-16) -> Self { var d = Self(0) var res = Self(1) guard self != 0 else { return 0 } guard n >= 1 else { return .nan } repeat { d = (self / res.power(n - 1) - res) / Self(n) res += d } while d >= epsilon * 10 || d <= -epsilon * 10 return res } } print(81.root(n: 4)) print(13.root(n: 5))
Private Function nth_root(y As Double, n As Double) Dim eps As Double: eps = 0.00000000000001 Dim x As Variant: x = 1 Do While True d = (y / x ^ (n - 1) - x) / n x = x + d e = eps * x If d > -e And d < e Then Exit Do End If Loop Debug.Print y; n; x; y ^ (1 / n) End Function Public Sub main() nth_root 1024, 10 nth_root 27, 3 nth_root 2, 2 nth_root 5642, 125 nth_root 7, 0.5 nth_root 4913, 3 nth_root 8, 3 nth_root 16, 2 nth_root 16, 4 nth_root 125, 3 nth_root 1000000000, 3 nth_root 1000000000, 9 End Sub
Change the programming language of this snippet from Swift to Go without modifying what it does.
extension FloatingPoint where Self: ExpressibleByFloatLiteral { @inlinable public func power(_ e: Int) -> Self { var res = Self(1) for _ in 0..<e { res *= self } return res } @inlinable public func root(n: Int, epsilon: Self = 2.220446049250313e-16) -> Self { var d = Self(0) var res = Self(1) guard self != 0 else { return 0 } guard n >= 1 else { return .nan } repeat { d = (self / res.power(n - 1) - res) / Self(n) res += d } while d >= epsilon * 10 || d <= -epsilon * 10 return res } } print(81.root(n: 4)) print(13.root(n: 5))
func root(a float64, n int) float64 { n1 := n - 1 n1f, rn := float64(n1), 1/float64(n) x, x0 := 1., 0. for { potx, t2 := 1/x, a for b := n1; b > 0; b >>= 1 { if b&1 == 1 { t2 *= potx } potx *= potx } x0, x = x, rn*(n1f*x+t2) if math.Abs(x-x0)*1e15 < x { break } } return x }
Write the same algorithm in C as shown in this Tcl implementation.
proc nthroot {n A} { expr {pow($A, 1.0/$n)} }
#include <stdio.h> #include <float.h> double pow_ (double x, int e) { int i; double r = 1; for (i = 0; i < e; i++) { r *= x; } return r; } double root (int n, double x) { double d, r = 1; if (!x) { return 0; } if (n < 1 || (x < 0 && !(n&1))) { return 0.0 / 0.0; } do { d = (x / pow_(r, n - 1) - r) / n; r += d; } while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10); return r; } int main () { int n = 15; double x = pow_(-3.14159, 15); printf("root(%d, %g) = %g\n", n, x, root(n, x)); return 0; }
Port the provided Tcl code into C# while preserving the original functionality.
proc nthroot {n A} { expr {pow($A, 1.0/$n)} }
static void Main(string[] args) { Console.WriteLine(NthRoot(81,2,.001)); Console.WriteLine(NthRoot(1000,3,.001)); Console.ReadLine(); } public static double NthRoot(double A,int n, double p) { double _n= (double) n; double[] x = new double[2]; x[0] = A; x[1] = A/_n; while(Math.Abs(x[0] -x[1] ) > p) { x[1] = x[0]; x[0] = (1/_n)*(((_n-1)*x[1]) + (A/Math.Pow(x[1],_n-1))); } return x[0]; }
Generate a C++ translation of this Tcl snippet without changing its computational steps.
proc nthroot {n A} { expr {pow($A, 1.0/$n)} }
double NthRoot(double m_nValue, double index, double guess, double pc) { double result = guess; double result_next; do { result_next = (1.0/index)*((index-1.0)*result+(m_nValue)/(pow(result,(index-1.0)))); result = result_next; pc--; }while(pc>1); return result; };
Convert this Tcl block to Java, preserving its control flow and logic.
proc nthroot {n A} { expr {pow($A, 1.0/$n)} }
public static double nthroot(int n, double A) { return nthroot(n, A, .001); } public static double nthroot(int n, double A, double p) { if(A < 0) { System.err.println("A < 0"); return -1; } else if(A == 0) { return 0; } double x_prev = A; double x = A / n; while(Math.abs(x - x_prev) > p) { x_prev = x; x = ((n - 1.0) * x + A / Math.pow(x, n - 1.0)) / n; } return x; }
Convert this Tcl snippet to Python and keep its semantics consistent.
proc nthroot {n A} { expr {pow($A, 1.0/$n)} }
from decimal import Decimal, getcontext def nthroot (n, A, precision): getcontext().prec = precision n = Decimal(n) x_0 = A / n x_1 = 1 while True: x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1)))) if x_0 == x_1: return x_1
Can you help me rewrite this code in VB instead of Tcl, keeping it the same logically?
proc nthroot {n A} { expr {pow($A, 1.0/$n)} }
Private Function nth_root(y As Double, n As Double) Dim eps As Double: eps = 0.00000000000001 Dim x As Variant: x = 1 Do While True d = (y / x ^ (n - 1) - x) / n x = x + d e = eps * x If d > -e And d < e Then Exit Do End If Loop Debug.Print y; n; x; y ^ (1 / n) End Function Public Sub main() nth_root 1024, 10 nth_root 27, 3 nth_root 2, 2 nth_root 5642, 125 nth_root 7, 0.5 nth_root 4913, 3 nth_root 8, 3 nth_root 16, 2 nth_root 16, 4 nth_root 125, 3 nth_root 1000000000, 3 nth_root 1000000000, 9 End Sub
Convert this Tcl block to Go, preserving its control flow and logic.
proc nthroot {n A} { expr {pow($A, 1.0/$n)} }
func root(a float64, n int) float64 { n1 := n - 1 n1f, rn := float64(n1), 1/float64(n) x, x0 := 1., 0. for { potx, t2 := 1/x, a for b := n1; b > 0; b >>= 1 { if b&1 == 1 { t2 *= potx } potx *= potx } x0, x = x, rn*(n1f*x+t2) if math.Abs(x-x0)*1e15 < x { break } } return x }
Preserve the algorithm and functionality while converting the code from Rust to PHP.
fn nthRoot(n: f64, A: f64) -> f64 { let p = 1e-9_f64 ; let mut x0 = A / n ; loop { let mut x1 = ( (n-1.0) * x0 + A / f64::powf(x0, n-1.0) ) / n; if (x1-x0).abs() < (x0*p).abs() { return x1 }; x0 = x1 } } fn main() { println!("{}", nthRoot(3. , 8. )); }
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Produce a functionally identical PHP code for the snippet given in Ada.
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Nth_Root is generic type Real is digits <>; function Nth_Root (Value : Real; N : Positive) return Real; function Nth_Root (Value : Real; N : Positive) return Real is type Index is mod 2; X : array (Index) of Real := (Value, Value); K : Index := 0; begin loop X (K + 1) := ( (Real (N) - 1.0) * X (K) + Value / X (K) ** (N-1) ) / Real (N); exit when X (K + 1) >= X (K); K := K + 1; end loop; return X (K + 1); end Nth_Root; function Long_Nth_Root is new Nth_Root (Long_Float); begin Put_Line ("1024.0 10th =" & Long_Float'Image (Long_Nth_Root (1024.0, 10))); Put_Line (" 27.0 3rd =" & Long_Float'Image (Long_Nth_Root (27.0, 3))); Put_Line (" 2.0 2nd =" & Long_Float'Image (Long_Nth_Root (2.0, 2))); Put_Line ("5642.0 125th =" & Long_Float'Image (Long_Nth_Root (5642.0, 125))); end Test_Nth_Root;
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Write the same code in PHP as shown below in Arturo.
nthRoot: function [a,n][ N: to :floating n result: a x: a / N while [0.000000000000001 < abs result-x][ x: result result: (1//n) * add (n-1)*x a/pow x n-1 ] return result ] print nthRoot 34.0 5 print nthRoot 42.0 10 print nthRoot 5.0 2
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Produce a language-to-language conversion: from AutoHotKey to PHP, same semantics.
p := 0.000001 MsgBox, % nthRoot( 10, 7131.5**10, p) "`n" . nthRoot( 5, 34.0 , p) "`n" . nthRoot( 2, 2 , p) "`n" . nthRoot(0.5, 7 , p) "`n" nthRoot(n, A, p) {  x1 := A x2 := A / n While Abs(x1 - x2) > p { x1 := x2 x2 := ((n-1)*x2+A/x2**(n-1))/n } Return, x2 }
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Port the provided AWK code into PHP while preserving the original functionality.
BEGIN { print nthroot(8,3) print nthroot(16,2) print nthroot(16,4) print nthroot(125,3) print nthroot(3,3) print nthroot(3,2) } function nthroot(y,n) { eps = 1e-15; x = 1; do { d = ( y / ( x^(n-1) ) - x ) / n ; x += d; e = eps*x; } while ( d < -e || d > e ) return x }
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Maintain the same structure and functionality when rewriting this code in PHP.
*FLOAT 64 @% = &D0D PRINT "Cube root of 5 is "; FNroot(3, 5, 0) PRINT "125th root of 5643 is "; FNroot(125, 5643, 0) END DEF FNroot(n%, a, d) LOCAL x0, x1 : x0 = a / n% : REPEAT x1 = ((n% - 1)*x0 + a/x0^(n%-1)) / n% SWAP x0, x1 UNTIL ABS (x0 - x1) <= d = x0
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Maintain the same structure and functionality when rewriting this code in PHP.
(ns test-project-intellij.core (:gen-class)) (defn abs [x] " Absolute value" (if (< x 0) (- x) x)) (defn power [x n] " x to power n, where n = 0, 1, 2, ... " (apply * (repeat n x))) (defn calc-delta [A x n] " nth rooth algorithm delta calculation " (/ (- (/ A (power x (- n 1))) x) n)) (defn nth-root " nth root of algorithm: A = numer, n = root" ([A n] (nth-root A n 0.5 1.0)) ([A n guess-prev guess-current] (if (< (abs (- guess-prev guess-current)) 1e-6) guess-current (recur A n guess-current (+ guess-current (calc-delta A guess-current n))))))
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Rewrite the snippet below in PHP so it works the same as the original Common_Lisp code.
(defun nth-root (n a &optional (epsilon .0001) (guess (1- n))) (assert (and (> n 1) (> a 0))) (flet ((next (x) (/ (+ (* (1- n) x) (/ a (expt x (1- n)))) n))) (do* ((xi guess xi+1) (xi+1 (next xi) (next xi))) ((< (abs (- xi+1 xi)) epsilon) xi+1))))
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Translate the given D code snippet into PHP without altering its behavior.
import std.stdio, std.math; real nthroot(in int n, in real A, in real p=0.001) pure nothrow { real[2] x = [A, A / n]; while (abs(x[1] - x[0]) > p) x = [x[1], ((n - 1) * x[1] + A / (x[1] ^^ (n-1))) / n]; return x[1]; } void main() { writeln(nthroot(10, 7131.5 ^^ 10)); writeln(nthroot(6, 64)); }
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Keep all operations the same but rewrite the snippet in PHP.
USES Math; function NthRoot(A, Precision: Double; n: Integer): Double; var x_p, X: Double; begin x_p := Sqrt(A); while Abs(A - Power(x_p, n)) > Precision do begin x := (1/n) * (((n-1) * x_p) + (A/(Power(x_p, n - 1)))); x_p := x; end; Result := x_p; end;
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Write the same algorithm in PHP as shown in this Elixir implementation.
defmodule RC do def nth_root(n, x, precision \\ 1.0e-5) do f = fn(prev) -> ((n - 1) * prev + x / :math.pow(prev, (n-1))) / n end fixed_point(f, x, precision, f.(x)) end defp fixed_point(_, guess, tolerance, next) when abs(guess - next) < tolerance, do: next defp fixed_point(f, _, tolerance, next), do: fixed_point(f, next, tolerance, f.(next)) end Enum.each([{2, 2}, {4, 81}, {10, 1024}, {1/2, 7}], fn {n, x} -> IO.puts " end)
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Produce a functionally identical PHP code for the snippet given in Erlang.
fixed_point(F, Guess, Tolerance) -> fixed_point(F, Guess, Tolerance, F(Guess)). fixed_point(_, Guess, Tolerance, Next) when abs(Guess - Next) < Tolerance -> Next; fixed_point(F, _, Tolerance, Next) -> fixed_point(F, Next, Tolerance, F(Next)).
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Produce a functionally identical PHP code for the snippet given in F#.
let nthroot n A = let rec f x = let m = n - 1. let x' = (m * x + A/x**m) / n match abs(x' - x) with | t when t < abs(x * 1e-9) -> x' | _ -> f x' f (A / double n) [<EntryPoint>] let main args = if args.Length <> 2 then eprintfn "usage: nthroot n A" exit 1 let (b, n) = System.Double.TryParse(args.[0]) let (b', A) = System.Double.TryParse(args.[1]) if (not b) || (not b') then eprintfn "error: parameter must be a number" exit 1 printf "%A" (nthroot n A) 0
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Transform the following Factor implementation into PHP, maintaining the same output and logic.
USING: kernel locals math math.functions prettyprint ; :: th-root ( a n -- a^1/n ) a [ a over n 1 - ^ /f over n 1 - * + n /f swap over 1e-5 ~ not ] loop ; 34 5 th-root . 34 5 recip ^ .
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Produce a language-to-language conversion: from Forth to PHP, same semantics.
: th-root { F: a F: n -- a^1/n } a begin a fover n 1e f- f** f/ fover n 1e f- f* f+ n f/ fswap fover 1e-5 f~ until ; 34e 5e th-root f. 34e 5e 1/f f** f.
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Write the same algorithm in PHP as shown in this Fortran implementation.
program NthRootTest implicit none print *, nthroot(10, 7131.5**10) print *, nthroot(5, 34.0) contains function nthroot(n, A, p) real :: nthroot integer, intent(in) :: n real, intent(in) :: A real, intent(in), optional :: p real :: rp, x(2) if ( A < 0 ) then stop "A < 0" elseif ( A == 0 ) then nthroot = 0 return end if if ( present(p) ) then rp = p else rp = 0.001 end if x(1) = A x(2) = A/n do while ( abs(x(2) - x(1)) > rp ) x(1) = x(2) x(2) = ((n-1.0)*x(2) + A/(x(2) ** (n-1.0)))/real(n) end do nthroot = x(2) end function nthroot end program NthRootTest
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Translate this program into PHP but keep the logic exactly as in Groovy.
import static Constants.tolerance import static java.math.RoundingMode.HALF_UP def root(double base, double n) { double xOld = 1 double xNew = 0 while (true) { xNew = ((n - 1) * xOld + base/(xOld)**(n - 1))/n if ((xNew - xOld).abs() < tolerance) { break } xOld = xNew } (xNew as BigDecimal).setScale(7, HALF_UP) }
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Write a version of this Haskell function in PHP with identical behavior.
n `nthRoot` x = fst $ until (uncurry(==)) (\(_,x0) -> (x0,((n-1)*x0+x/x0**(n-1))/n)) (x,x/n)
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Transform the following Icon implementation into PHP, maintaining the same output and logic.
procedure main() showroot(125,3) showroot(27,3) showroot(1024,10) showroot(39.0625,4) showroot(7131.5^10,10) end procedure showroot(a,n) printf("%i-th root of %i = %i\n",n,a,root(a,n)) end procedure root(a,n,p) if n < 0 | type(n) !== "integer" then runerr(101,n) if a < 0 then runerr(205,a) /p := 1e-14 xn := a / real(n) while abs(a - xn^n) > p do xn := ((n - 1) * (xi := xn) + a / (xi ^ (n-1))) / real(n) return xn end link printf
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Write the same algorithm in PHP as shown in this J implementation.
'`N X NP' =. (0 { [)`(1 { [)`(2 { [) iter =. N %~ (NP * ]) + X % ] ^ NP nth_root =: (, , _1+[) iter^:_ f. ] 10 nth_root 7131.5^10 7131.5
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Change the following Julia code into PHP without altering its purpose.
function nthroot(n::Integer, r::Real) r < 0 || n == 0 && throw(DomainError()) n < 0 && return 1 / nthroot(-n, r) r > 0 || return 0 x = r / n prevdx = r while true y = x ^ (n - 1) dx = (r - y * x) / (n * y) abs(dx) ≥ abs(prevdx) && return x x += dx prevdx = dx end end @show nthroot.(-5:2:5, 5.0) @show nthroot.(-5:2:5, 5.0) - 5.0 .^ (1 ./ (-5:2:5))
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Keep all operations the same but rewrite the snippet in PHP.
function nroot(root, num) return num^(1/root) end
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Keep all operations the same but rewrite the snippet in PHP.
Root[A,n]
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Port the following code from MATLAB to PHP with equivalent syntax and logic.
function answer = nthRoot(number,root) format long answer = number / root; guess = number; while not(guess == answer) guess = answer; answer = (1/root)*( ((root - 1)*guess) + ( number/(guess^(root - 1)) ) ); end end
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Preserve the algorithm and functionality while converting the code from Nim to PHP.
import math proc nthRoot(a: float; n: int): float = var n = float(n) result = a var x = a / n while abs(result-x) > 1e-15: x = result result = (1/n) * (((n-1)*x) + (a / pow(x, n-1))) echo nthRoot(34.0, 5) echo nthRoot(42.0, 10) echo nthRoot(5.0, 2)
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Translate this program into PHP but keep the logic exactly as in OCaml.
let nthroot ~n ~a ?(tol=0.001) () = let nf = float n in let nf1 = nf -. 1.0 in let rec iter x = let x' = (nf1 *. x +. a /. (x ** nf1)) /. nf in if tol > abs_float (x -. x') then x' else iter x' in iter 1.0 ;; let () = Printf.printf "%g\n" (nthroot 10 (7131.5 ** 10.0) ()); Printf.printf "%g\n" (nthroot 5 34.0 ()); ;;
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Please provide an equivalent version of this Perl code in PHP.
use strict; sub nthroot ($$) { my ( $n, $A ) = @_; my $x0 = $A / $n; my $m = $n - 1.0; while(1) { my $x1 = ($m * $x0 + $A / ($x0 ** $m)) / $n; return $x1 if abs($x1 - $x0) < abs($x0 * 1e-9); $x0 = $x1; } }
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Change the following PowerShell code into PHP without altering its purpose.
$epsilon=1E-10 function power($x,$e){ $ret=1 for($i=1;$i -le $e;$i++){ $ret*=$x } return $ret } function root($y,$n){ if (0+$n -lt 0){$tmp=-$n} else {$tmp=$n} $ans=1 do{ $d = ($y/(power $ans ($tmp-1)) - $ans)/$tmp $ans+=$d } while ($d -lt -$epsilon -or $d -gt $epsilon) if (0+$n -lt 0){return 1/$ans} else {return $ans} } root 625 2 root 2401 4 root 2 -2 root 1.23456789E-20 34 root 9.87654321E20 10 ((root 5 2)+1)/2 ((root 5 2)-1)/2
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Convert this R block to PHP, preserving its control flow and logic.
nthroot <- function(A, n, tol=sqrt(.Machine$double.eps)) { ifelse(A < 1, x0 <- A * n, x0 <- A / n) repeat { x1 <- ((n-1)*x0 + A / x0^(n-1))/n if(abs(x1 - x0) > tol) x0 <- x1 else break } x1 } nthroot(7131.5^10, 10) nthroot(7, 0.5)
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Preserve the algorithm and functionality while converting the code from Racket to PHP.
#lang racket (define (nth-root number root (tolerance 0.001)) (define (acceptable? next current) (< (abs (- next current)) tolerance)) (define (improve current) (/ (+ (* (- root 1) current) (/ number (expt current (- root 1)))) root)) (define (loop current) (define next-guess (improve current)) (if (acceptable? next-guess current) next-guess (loop next-guess))) (loop 1.0))
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Convert this COBOL snippet to PHP and keep its semantics consistent.
IDENTIFICATION DIVISION. PROGRAM-ID. Nth-Root. AUTHOR. Bill Gunshannon. INSTALLATION. DATE-WRITTEN. 4 Feb 2020. ************************************************************ ** Program Abstract: ** Compute the Nth Root of a positive real number. ** ** Takes values from console. If Precision is left ** blank defaults to 0.001. ** ** Enter 0 for first value to terminate program. ************************************************************ ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT Root-File ASSIGN TO "Root-File" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD Root-File DATA RECORD IS Parameters. 01 Parameters. 05 Root PIC 9(5). 05 Num PIC 9(5)V9(5). 05 Precision PIC 9V9(9). WORKING-STORAGE SECTION. 01 TEMP0 PIC 9(9)V9(9). 01 TEMP1 PIC 9(9)V9(9). 01 RESULTS. 05 Field1 PIC ZZZZZ.ZZZZZ. 05 FILLER PIC X(5). 05 Field2 PIC ZZZZ9. 05 FILLER PIC X(14). 05 Field3 PIC 9.999999999. 01 HEADER. 05 FILLER PIC X(72) VALUE " Number Root Precision.". 01 Disp-Root PIC ZZZZZ.ZZZZZ. PROCEDURE DIVISION. Main-Program. PERFORM FOREVER PERFORM Get-Input IF Precision = 0.0 THEN MOVE 0.001 to Precision END-IF PERFORM Compute-Root MOVE Root TO Field2 MOVE Num TO Field1 MOVE Precision TO Field3 DISPLAY HEADER DISPLAY RESULTS DISPLAY " " MOVE TEMP1 TO Disp-Root DISPLAY "The Root is: " Disp-Root END-PERFORM. Get-Input. DISPLAY "Input Base Number: " WITH NO ADVANCING ACCEPT Num IF Num EQUALS ZERO THEN DISPLAY "Good Bye." STOP RUN END-IF DISPLAY "Input Root: " WITH NO ADVANCING ACCEPT Root DISPLAY "Input Desired Precision: " WITH NO ADVANCING ACCEPT Precision. Compute-Root. MOVE Root TO TEMP0 DIVIDE Num BY Root GIVING TEMP1 PERFORM UNTIL FUNCTION ABS(TEMP0 - TEMP1) LESS THAN Precision MOVE TEMP1 TO TEMP0 COMPUTE TEMP1 = (( Root - 1.0) * TEMP1 + Num / TEMP1 ** (Root - 1.0)) / Root END-PERFORM. END-PROGRAM.
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Can you help me rewrite this code in PHP instead of REXX, keeping it the same logically?
class nth_root method main(args=String[]) static if args.length < 2 then do say "at least 2 arguments expected" exit end x = args[0] root = args[1] if args.length > 2 then digs = args[2] if root=='' then root=2 if digs = null, digs = '' then digs=20 numeric digits digs say ' x = ' x say ' root = ' root say 'digits = ' digs say 'answer = ' root(x,root,digs) method root(x,r,digs) static --procedure; parse arg x,R 1 oldR R = r oldR = r if r=0 then do say say '*** error! ***' say "a root of zero can't be specified." say return '[n/a]' end R=R.abs() if x<0 & (R//2==0) then do say say '*** error! ***' say "an even root can't be calculated for a" - 'negative number,' say 'the result would be complex.' say return '[n/a]' end if x=0 | r=1 then return x/1 Rm1=R-1 oldDigs=digs dm=oldDigs+5 ax=x.abs() g=(ax+1)/r**r -- numeric fuzz 3 d=5 loop forever d=d+d if d>dm then d = dm numeric digits d old=0 loop forever _=(Rm1*g**R+ax)/R/g**rm1 if _=g | _=old then leave old=g g=_ end if d==dm then leave end _=g*x.sign() if oldR<0 then return _=1/_ numeric digits oldDigs return _/1
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Rewrite this program in PHP while keeping its functionality equivalent to the Ruby version.
def nthroot(n, a, precision = 1e-5) x = Float(a) begin prev = x x = ((n - 1) * prev + a / (prev ** (n - 1))) / n end while (prev - x).abs > precision x end p nthroot(5,34)
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Keep all operations the same but rewrite the snippet in PHP.
fun nthRoot(x: Double, n: Int): Double { if (n < 2) throw IllegalArgumentException("n must be more than 1") if (x <= 0.0) throw IllegalArgumentException("x must be positive") val np = n - 1 fun iter(g: Double) = (np * g + x / Math.pow(g, np.toDouble())) / n var g1 = x var g2 = iter(g1) while (g1 != g2) { g1 = iter(g1) g2 = iter(iter(g2)) } return g1 } fun main(args: Array<String>) { val numbers = arrayOf(1728.0 to 3, 1024.0 to 10, 2.0 to 2) for (number in numbers) println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}") }
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Convert the following code from Swift to PHP, ensuring the logic remains intact.
extension FloatingPoint where Self: ExpressibleByFloatLiteral { @inlinable public func power(_ e: Int) -> Self { var res = Self(1) for _ in 0..<e { res *= self } return res } @inlinable public func root(n: Int, epsilon: Self = 2.220446049250313e-16) -> Self { var d = Self(0) var res = Self(1) guard self != 0 else { return 0 } guard n >= 1 else { return .nan } repeat { d = (self / res.power(n - 1) - res) / Self(n) res += d } while d >= epsilon * 10 || d <= -epsilon * 10 return res } } print(81.root(n: 4)) print(13.root(n: 5))
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Maintain the same structure and functionality when rewriting this code in PHP.
proc nthroot {n A} { expr {pow($A, 1.0/$n)} }
function nthroot($number, $root, $p = P) { $x[0] = $number; $x[1] = $number/$root; while(abs($x[1]-$x[0]) > $p) { $x[0] = $x[1]; $x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root; } return $x[1]; }
Convert this C block to Rust, preserving its control flow and logic.
#include <stdio.h> #include <float.h> double pow_ (double x, int e) { int i; double r = 1; for (i = 0; i < e; i++) { r *= x; } return r; } double root (int n, double x) { double d, r = 1; if (!x) { return 0; } if (n < 1 || (x < 0 && !(n&1))) { return 0.0 / 0.0; } do { d = (x / pow_(r, n - 1) - r) / n; r += d; } while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10); return r; } int main () { int n = 15; double x = pow_(-3.14159, 15); printf("root(%d, %g) = %g\n", n, x, root(n, x)); return 0; }
fn nthRoot(n: f64, A: f64) -> f64 { let p = 1e-9_f64 ; let mut x0 = A / n ; loop { let mut x1 = ( (n-1.0) * x0 + A / f64::powf(x0, n-1.0) ) / n; if (x1-x0).abs() < (x0*p).abs() { return x1 }; x0 = x1 } } fn main() { println!("{}", nthRoot(3. , 8. )); }