如何计算一系列方程? [英] How to calculate a series of equations?

查看:43
本文介绍了如何计算一系列方程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个问题,如果我从一个文件中得到几个方程,例如:

na = 1.350拉姆达 = 0.2段 = 2*na*Lambdamag = 4结果 = mag+Seg*3

我怎样才能得到结果的真正价值?谢谢!

解决方案

嗯,你需要的是一点点解析和一点点映射,当然还有一些对 eval 的创造性使用.

>

#假设文件内容是一个大字符串,$equations数组集变量 {}设置地图{}foreach 行 [拆分 $equations "\n"] {if {![regexp {^ *(\w+) *= *(.*)$} $line ->var exp]} {错误非法行‘$line’"}set vars($var) [expr [字符串映射 $map $exp]]把计算的 $var 作为 $vars($var)"Lappend 地图 $var \$vars($var)}puts "result = $vars(result)"

现在的关键是:

  • regexp {^ *(\w+) *= *(.*)$} $line ->var exp

    解析一行以提取变量和要计算的表达式以获得变量的值.

  • expr [字符串映射 $map $exp]

    应用当前映射将 $exp 转换为 Tcl 表达式,并将结果计算为表达式.(形式上不安全,但真的在这里很方便!)

  • lappend map $var \$vars($var)

    更新映射转换以了解如何读取适当的变量.基本上,Lambda 在未来的表达式中将变成 $vars(Lambda).

I meet a question, if I get several equations from a file, for example :

na = 1.350
Lambda = 0.2
Seg = 2*na*Lambda
mag = 4
result = mag+Seg*3

how can I get the real value of the result? Thanks!

解决方案

Well, what you need is a little parsing and a little mapping and, of course, some creative use of eval.

# Assume that the contents of the file is in a big string, $equations

array set vars {}
set map {}
foreach line [split $equations "\n"] {
    if {![regexp {^ *(\w+) *= *(.*)$} $line -> var exp]} {
        error "illegal line '$line'"
    }
    set vars($var) [expr [string map $map $exp]]
    puts "computed $var as $vars($var)"
    lappend map $var \$vars($var)
}
puts "result = $vars(result)"

Now the key bits of this are:

  • regexp {^ *(\w+) *= *(.*)$} $line -> var exp

    Parses a line to extract the variable and the expression to compute to get the value of the variable.

  • expr [string map $map $exp]

    Applies the current mapping to turn $exp into a Tcl expression, and evaluates the result as an expression. (Formally unsafe, but really convenient here!)

  • lappend map $var \$vars($var)

    Updates the mapping transform to know how to read an appropriate variable. Basically, a Lambda will become $vars(Lambda) in future expressions.

这篇关于如何计算一系列方程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆