How to align output in columns?

Perhaps:

using DataFrame

df = DataFrame(n = Int[], n! = Int[], Approximation = Float64[], Ratio = Float64[])

for n in 1:10
    fact  = factorial(big(n))
    stir  = n^n * exp(-n) * sqrt(2 * π * n )
    ratio = Float32(fact/stir)
    push!(df, [n, fact, stir, ratio])
end

strwidths = [maximum(strwidth.(string.([df[:, i]; names(df)[i]]))) for i in 1:size(df, 2)]

io = IOBuffer()

# Print headers
for (i, header) in enumerate(names(df))
	print(io, rpad(header, strwidths[i]), "\t")
end
println(io)

for j in 1:size(df, 1)
	for i in 1:size(df, 2)
		print(io, rpad(df[j,i], strwidths[i]), "\t")
	end
	println(io)
end

print(String(take!(io)))

giving

n 	n!     	Approximation      	Ratio             	
1 	1      	0.9221370088957891 	1.084437608718872 	
2 	2      	1.9190043514889832 	1.04220712184906  	
3 	6      	5.836209591345864  	1.028064489364624 	
4 	24     	23.50617513289329  	1.0210082530975342	
5 	120    	118.01916795759008 	1.0167839527130127	
6 	720    	710.0781846421849  	1.0139728784561157	
7 	5040   	4980.395831612461  	1.0119677782058716	
8 	40320  	39902.3954526567   	1.0104656219482422	
9 	362880 	359536.87284194824 	1.0092984437942505	
10	3628800	3.598695618741036e6	1.0083653926849365	

The code is not very well polished but might give you a start.

7 Likes