浮点数数学运算
Float Number mathematical operation
我有一个 .txt 文件作为程序的输出,其中包含一些感兴趣的值。问题是在某些情况下,这些值的格式很奇怪,我无法对它们应用数学运算。
例如:我的文件包含这些数字:
-2.55622-3
-0.31-2
-3.225-2
...
这些数字在正常的数学格式中应该是:
-2.55622e-03
-0.31e-02
-3.225e-02
当然,如果我尝试对这些值求和,这就是错误:
can't use non-numeric string as operand of "+"
如何使用我的原始值进行操作?我真的没有想法。
请记住,我无法更改 .txt 文件的值格式
尝试用模式 (\d+.\d+)
注册子数字。
set fp [open "somefile.txt" r]
set file_data [read $fp]
close $fp
set data [split $file_data "\n"]
foreach line $data {
set e "e"
set number [ regexp -all -inline {(\d+.\d+)} $line ]
regsub -all {(\d+.\d+)} $number "$number$e" number
}
例如读取文件并按行分割。
set e "e"
查找号码:
set number [ regexp -all -inline {(\d+.\d+)} $line ]
然后替换
regsub -all {(\d+.\d+)} $number "$number$e" number
另一种方法:
% exec cat file
-2.55622-3
-0.31-2
-3.225-2
42
foo
% set fh [open "file" r]
% while {[gets $fh line] != -1} {
puts -nonewline "\"$line\"\t=> "
if {! [regsub {[-+]\d+$} [string trim $line] {e&} num]} {set num $line}
puts -nonewline "$num\t=> "
puts [expr {$num + 0}]
}
"-2.55622-3 " => -2.55622e-3 => -0.00255622
"-0.31-2" => -0.31e-2 => -0.0031
"-3.225-2" => -3.225e-2 => -0.03225
"42" => 42 => 42
can't use non-numeric string as operand of "+"
"foo" => foo => %
我有一个 .txt 文件作为程序的输出,其中包含一些感兴趣的值。问题是在某些情况下,这些值的格式很奇怪,我无法对它们应用数学运算。
例如:我的文件包含这些数字:
-2.55622-3
-0.31-2
-3.225-2
...
这些数字在正常的数学格式中应该是:
-2.55622e-03
-0.31e-02
-3.225e-02
当然,如果我尝试对这些值求和,这就是错误:
can't use non-numeric string as operand of "+"
如何使用我的原始值进行操作?我真的没有想法。 请记住,我无法更改 .txt 文件的值格式
尝试用模式 (\d+.\d+)
注册子数字。
set fp [open "somefile.txt" r]
set file_data [read $fp]
close $fp
set data [split $file_data "\n"]
foreach line $data {
set e "e"
set number [ regexp -all -inline {(\d+.\d+)} $line ]
regsub -all {(\d+.\d+)} $number "$number$e" number
}
例如读取文件并按行分割。
set e "e"
查找号码:
set number [ regexp -all -inline {(\d+.\d+)} $line ]
然后替换
regsub -all {(\d+.\d+)} $number "$number$e" number
另一种方法:
% exec cat file
-2.55622-3
-0.31-2
-3.225-2
42
foo
% set fh [open "file" r]
% while {[gets $fh line] != -1} {
puts -nonewline "\"$line\"\t=> "
if {! [regsub {[-+]\d+$} [string trim $line] {e&} num]} {set num $line}
puts -nonewline "$num\t=> "
puts [expr {$num + 0}]
}
"-2.55622-3 " => -2.55622e-3 => -0.00255622
"-0.31-2" => -0.31e-2 => -0.0031
"-3.225-2" => -3.225e-2 => -0.03225
"42" => 42 => 42
can't use non-numeric string as operand of "+"
"foo" => foo => %