循环后Julia的结果表现得很整齐

时间:2014-11-22 16:13:03

标签: julia

我在Julia中创建了一个小代码,可以使用function iteration来解决一个简单的非线性问题。

代码如下:

"""
Problem: find the root of f(x) = exp(-x) - x
using the fixed point iteration
(aka function iteration)

Solution: f(x) = exp(-x) - x = 0
          x = exp(-x)

"""

i = 0;              # initialize first iteration
x = 0;              # initialize solution
error = 1;          # initialize error bound
xvals = x;          # initialize array of iterates

tic()

while error >= 1e-10
        y = exp(-x);
        xvals = [xvals;y];      # It is not needed actually
        error = abs(y-x);
        x = y;
        i = i + 1;
        println(["Solution", x', "Error:", error', "Iteration no:", i'])
end

toc()

在上面的代码中,由于有许多十进制数,结果并不整齐。据我了解,使用println可能不是一个好主意,而必须使用@printfsprintf,但是,我无法将所有内容放在一行中。

有可能吗?

1 个答案:

答案 0 :(得分:3)

printf的语法(大致)对所有语言都相同, 但它确实是奥术。

您可以将%f用于浮点数,%e用于科学计数法中的浮点数, %d表示整数,%s表示字符串。 %和字母之间的数字是 逗号前后的位数(或字符)。

i = 0
x = 0
error = Inf
while error >= 1e-10
    x, previous = exp(-x), x
    error = abs( x - previous )
    i += 1
    @printf( 
      "Value: %1.3f  Error: %1.3e  Iteration: %3d\n", 
      x, error, i 
    )
end

您也可以尝试roundsignif, 但由于圆十进制数不能总是完全表示为浮点数, 这不能可靠地运作。