1

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.

user3840170
  • 26,597
  • 4
  • 30
  • 62
TheBatz
  • 115
  • 2
  • 12
  • 6
    `^` is not an exponentiation operator, but bitwise XOR. You may have meant to write `1e-8` – user3840170 Jan 20 '22 at 13:07
  • I can't believe that's the solution... I have been using .powi() and num::pow() everywhere in my code but there. Thank you very much! – TheBatz Jan 20 '22 at 13:13
  • Does this answer your question? [How to raise a number to a power?](https://stackoverflow.com/questions/51208703/how-to-raise-a-number-to-a-power) – Matthias Braun Feb 07 '23 at 18:51

1 Answers1

5

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.

user3840170
  • 26,597
  • 4
  • 30
  • 62