首页 > 解决方案 > 在powershell中有一种方法可以使用乘法将正数变为负数吗?

问题描述

我想知道是否有一种方法可以使用乘法将正数变为负数,就像$b = $a * -1
我正在寻找最成本合理的方式一样,因为我将在脚本中多次这样做。

-edit 此时我正在使用它,但在计算方面看起来非常昂贵:

    $temp_array = New-Object 'object[,]' $this.row,$this.col

    for ($i=0;$i -le $this.row -1 ; $i++) {
        for ($j=0;$j -le $this.col -1 ; $j++) {
            $digit = $this.data[$i,$j] * -1
            $temp_array[$i,$j] = 1 / ( 1 + [math]::exp( $digit ) )
            #[math]::Round( $digit ,3)
        }
    }
    $this.data = $temp_array

标签: powershellnegative-number

解决方案


要将正数无条件地转换为负数(或者更一般地,翻转数字的符号),只需使用一元运算-

 PS> $v = 10; -$v
 -10

适用于您的案例:

 $digit = -$this.data[$i,$j]

顺便说一句:如果性能很重要,您可以通过使用范围表达式来创建要迭代的索引来加速循环,尽管以内存消耗为代价:

$temp_array = New-Object 'object[,]' $this.row,$this.col

for ($i in 0..($this.row-1)) {
    for ($j in 0..($this.col-1)) {
        $digit = - $this.data[$i,$j]
        $temp_array[$i,$j] = 1 / ( 1 + [math]::exp( $digit ) )
    }
}
$this.data = $temp_array

推荐阅读