rustexponentiationbitwise-xor

When I try to use the exponentiation operator in Rust, it gives strange results. Why?


I am trying to implement Complex-Step Differentiation in Rust. However, when raising the complex number to a power higher than 2, I get a completely different result than Julia. The algorithm works in Julia for any function but in Rust, it only works for second-order functions.

Here are the ways I raise the imaginary number to a power in both languages.

In Rust:

let x: f64 = 1.0;
let h: f64 = f64::from(1*10^-8);

println!("Result = {:?}", (num::pow(Complex::new(x,h),3));
// Complex { re: -587.0, im: 2702.0 }

In Julia:

h = 1*10^-8
x = 1
println((x+im*h)^3)
# 0.9999999999999997 + 3.000000000000001e-8im

I have no idea as to how I could do this so any help is very welcome.


Solution

  • Rust has no exponentiation operator.

    The binary operator ^ is not exponentiation, but bitwise exclusive-or. This is an operation defined only for integer types, and it returns the number whose set of set bits is the symmetric difference of the sets of set bits of the operands. 1 * 10 ^ -8 thus computes (assuming the 32-bit signed type, which is what type inference assigns to this expression by default) 0x0000000a0xfffffff8, which is 0xfffffff2, i.e. −14.

    If you want to specify a floating-point number in exponential notation, you can use the E notation:

    let h: f64 = 1e-8;
    

    For arbitrary exponentiation, since you already have the num crate, you might as well use num::pow.