【问题标题】:How do I raise a float to an exponent in OCaml?如何在 OCaml 中将浮点数提高到指数?
【发布时间】:2020-01-26 07:14:18
【问题描述】:

我正在尝试编写一个函数,它接受 x 并将其提升到 n 的幂。

如果 x 和 n 是整数,则此代码有效:

let rec pow x n =
if n == 0 then 1 else
if (n mod 2 = 0) then pow x (n/2) * pow x (n/2) else
x * pow x (n/2) * pow x (n/2);;

如果我尝试在 x 是浮点数的情况下更改代码以使其正常工作,它就会崩溃:

let rec float_pow x n =
if n == 0.0 then 1.0 else
if n mod_float 2.0 == 0.0 then float_pow x (n /. 2) *. float_pow x (n /. 2) else
x *. float_pow x (n /. 2) *. float_pow x (n /. 2);;

我收到此错误:

Error: This expression has type float
   This is not a function; it cannot be applied.

我该怎么办?

【问题讨论】:

  • 对于OCaml中只想将值升为指数的,对应的操作符在OCaml中称为**,因此x^n编码为x ** n,例如2.0 ** 3.14 .

标签: recursion functional-programming ocaml


【解决方案1】:

我认为关键问题是mod 是OCaml 中的关键字,并且被视为中缀运算符。但是mod_float只是一个普通的函数。您需要以前缀形式使用它。

所以x mod n 应该翻译成mod_float x n

您还有另一个问题,那就是您正在使用专用的== 运算符进行相等比较。您想在 OCaml 中使用 = 进行相等比较,除非您需要“物理”比较(这不是您想要的)。

这不仅仅是风格 - 它真的很重要。请注意以下结果:

# 0.0 == 0.0;;
- : bool = false
# 0.0 = 0.0;;
- : bool = true

【讨论】:

    猜你喜欢
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多