有没有一种方法可以从Chapel数组中打印格式化表格?

3

我正在处理一个教堂内的热传递问题,虽然我知道无法得到一个好用的图形用户界面(GUI),但我希望至少能够打印出一些东西,让我能够看到运行代码后的结果。到目前为止,我的输出很难阅读,因为数字过长会推出整个行。我想使用格式化输入/输出(formattedIO),但是文档对我来说很难理解,并且似乎更专注于单行格式化而不是与表格相关的任何内容。我希望有一种方法可以确保所有列都对齐。如果我的代码有帮助的话,请提供一下,谢谢!

use Math;
use Time;

var rows = 10;
var cols = 10;

var times = 4;

var x = 5;
var y = 5;

var temps: [0..rows+1, 0..cols+1] real = 0;
var past: [0..rows+1, 0..cols+1] real;

temps[x,y] = 100;
past[x,y] = 100;

var t: Timer;
t.start();

for t in 1..times do {
  forall i in 1..rows do {
    for j in 1..cols do {
      temps[i,j] = floor((past[i-1,j]+past[i+1,j]+past[i,j-1]+past[i,j+1])/4);
      //floor was used to cut off extra decimals in an attempt to make the display better
    }
  }
  past = temps;
}

t.stop();
writeln(t.elapsed());
writeln(temps);

通常网格要大得多(1000×1000),但我把它缩小了,这样我就可以看到这些值。我真的很希望找到一种方法,以使更大的网格可以以不那么糟糕的方式打印出来。也许需要使用文件输出来处理更大的网格尺寸吗?

1个回答

3

希望有一个用于打印格式化表格的库,但我目前还不知道是否已经有这样的库。

目前,您可以计算每个表格单元格的宽度,然后使用格式化字符串指定填充到最大宽度。以下是一个示例:

use IO;

var data:[1..5, 1..5] real;

// Compute some numbers that need formatting help
for (ij,elt) in zip(data.domain, data) {
  var (i, j) = ij;
  if i == j {
    elt = 0.0;
  } else {
    var d = i-j;
    elt = d*d*d*17.20681 - j*0.1257201;
  }
}

// %r tries to use e.g. 12.25 and exponential for big/small
// here "r" is for "real"
// %dr ("decimal real") means always like 12.25
// %er ("exponential real") is always like 1.2e27
// and %{####.####} is available to show the pattern you want
// but will never output in exponential

// Note that you can specify padding:
//  %17r would be padded on the left with spaces to 17 columns
//  %017r would be padded on the left with zeros to 17 columns
//  %-17r would be padded on the right with spaces to 17 columns
// You can also use %*r to specify the padding in an argument

// Let's compute the maximum number of characters for each element
// This uses the string.format function
//  https://chapel-lang.org/docs/master/modules/standard/IO/FormattedIO.html#FormattedIO.string.format
// as well as promotion.

// compute the maximum size of any field
// (this could be adapted to be per-column, say)
var width = 0;
for i in data.domain.dim(0) {
  for j in data.domain.dim(1) {
    var mywidth = "%r".format(data[i,j]).size;
    if width < mywidth then
      width = mywidth;
  }
}
 
// Now format all of the elements with that size
for i in data.domain.dim(0) {
  var first = true;
  for j in data.domain.dim(1) {
    if first==false then
      write(" ");
    writef("%*r", width, data[i,j]);
    first = false;
  }
  writeln();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接