High Precision Metallic Means

dc, 12

?kdd*4+v+2/p
  • ? Push n and p onto the stack
  • k set precision to p
  • dd duplicate n twice (total three copies)
  • * multiply n*n
  • 4+ add 4
  • v take square root
  • + add n (last copy on stack)
  • 2/ divide by 2
  • p print

Testcase:

$ dc -f metalmean.dc <<< "1 9"
1.618033988
$

R, 116 bytes

library(Rmpfr);s=scan();n=mpfr(s[1],1e6);r=(n+(4+n^2)^.5)/2;t=toString(format(r,s[2]+2));cat(substr(t,1,nchar(t)-1))

This reads two integers from STDIN and prints the result to STDOUT. You can try it online.

Ungolfed + explanation:

# Import the Rmpfr library for arbitrary precision floating point arithmetic
library(Rmpfr)

# Read two integers from STDIN
s <- scan()

# Set n equal to the first input as an mpfr object with 1e6 bits of precision
n <- mpfr(s[1], 1e6)

# Compute the result using the basic formula
r <- (n + sqrt(4 + n^2)) / 2

# Get the rounded string representation of r with 1 more digit than necessary
t <- toString(format(r, s[2] + 2))

# Print the result with p unrounded digits
cat(substr(t, 1, nchar(t) - 1))

If you don't have the Rmpfr library installed, you can install.packages("Rmpfr") and all of your dreams will come true.

Tags:

Code Golf