Sqrt function

Tip / Sign in to post questions, reply, level up, and achieve exciting badges. Know more

cross mob
Not applicable
Hi,
Target : XMC1300 boot kit
Problem : sqrt function takes more time for execution
I have a XMC1300 boot kit and include math.h library to the project.
I am trying to run instruction sqrt(x).
But this instruction takes around 120us for execution.
Is there any way to reduce this execution time interval using FASTMATH or other library?
How to include that library to my project?
Regard,
Naresh
0 Likes
3 Replies
Not applicable
You can write your own sqrt function where you have control over the number of iterations.

It's basically a logarithmic search.


#define SQRT_ITERATIONS 16

float sqrt_fast(float const x) {
float low, high, root, val;
int i;

if (x == 1.f) {
return x;
}

/* You might want to treat x < 0 here ... */

root = (1.f + x) / 2.f;
if (x < 1.f) {
low = x;
high = 1.f;
} else {
low = 1.f;
high = x;
}

for (i = 0; i < SQRT_ITERATIONS; ++i) {
val = root * root;
if (val == x) {
return root;
} else if (val < x) {
low = root;
} else {
high = root;
}
root = (high + low) / 2.f;
}
return root;
}


With SQRT_ITERATIONS set to 2, sqrt_fast(4) would return 2.125.
Each step adds precision, with SQRT_ITERATIONS you can tune the function between precision and speed.

I wrote this off my head, so this is untested code.
0 Likes
Not applicable
Thanks,
I have trying this function as you have suggested, but this takes more time up to 500us.
This is not excepted.
I am using with xmc1300 fixed point unit.
Is there any other solution for sqrt function for a fixed point unit which executes in a time as low as possible?

Regards,
Naresh
0 Likes
Not applicable
As I said, you just have to select a lower value for SQRT_ITERATIONS. How low you can go depends on your precision requirements.

There's no way to get a fast and precise sqrt unless you have a lookup table.

How does the fixed point format look like? I mean how many bits in front and behind the dot?

Do you have an expected range of input values?

It might be possible to make a lookup table for a subset of the value range to shorten the search.
0 Likes