Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 XOR. 1 * 10 ^ -8 thus computes 0x0000000a ^ 0xfffffff8, 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 for that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading