gpt4 book ai didi

math - Ada:不能对浮点变量求平方

转载 作者:行者123 更新时间:2023-12-04 05:53:36 25 4
gpt4 key购买 nike

我遇到了一个令人惊讶的行为,因为我无法接受 square power的一个变量。 Ada允许 square power的实际值(value)虽然。下面是我的示例代码:

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Long_Float_Text_IO;
with Ada.Float_Text_IO;
with Ada.Numerics.Long_Elementary_Functions;
use Ada.Numerics.Long_Elementary_Functions;


procedure Test_power is

testing : constant := -0.11603;


begin

Ada.Text_IO.Put("Works fine with numerical value entered directly: ");
Ada.Long_Float_Text_IO.Put (Item => -0.11603 ** 2.0, Fore => 3, Aft => 5, Exp => 0);
Ada.Text_IO.New_Line;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put("This does not work: ");
Ada.Long_Float_Text_IO.Put (Item => testing ** 2.0, Fore => 3, Aft => 5, Exp => 0);

end Test_power;
output屏幕上是:
Works fine with numerical value entered directly:  -0.01346

This does not work:


Execution terminated by unhandled exception
Exception name: ADA.NUMERICS.ARGUMENT_ERROR
Message: a-ngelfu.adb:96 instantiated at a-nlelfu.ads:18
Call stack traceback locations:
0x413ed5 0x42771d 0x427a2a 0x4010b4 0x401146 0x7c817075

编译是使用以下方法完成的:
GPS 4.4.1 (20091215) hosted on i686-pc-mingw32
GNAT GPL 2010 (20100603)

两个问题:

(a) 当我服用 testing ** 2.0 时我做错了什么?

(b) -0.11603的平方正 0.01346 .那么为什么我的第一个输出中也得到了负号?

经过一些额外的测试:

如果我只取正值 0.11603 ,然后输出(它的平方)给出

(a) -0.01346(b) 0.01346
这可能意味着问题的一部分在于 negative sign .

非常感谢...

最佳答案

"**"运算符引发 Numerics.Operator_Error当左操作数为负时,或当两个操作数的值都为零时。

当正确的操作数在数学上是一个像 2.0 这样的精确整数时,期望它能够工作并不是不合理的。 ,但对于非整数指数,数学结果是复数,而 Ada.Numerics.Generic_Elementary_Functions不会将恰好是精确整数的实数视为特殊情况。

如果您只想做一个数字的平方,请使用内置的 "**"带有整数指数的运算符。换句话说,改变这个:

testing ** 2.0

对此:
testing ** 2

关于math - Ada:不能对浮点变量求平方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9778148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com