无幂函数的浮点数求幂

编程入门 行业动态 更新时间:2024-10-23 22:25:29
本文介绍了无幂函数的浮点数求幂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当前,我必须在电源操作员被窃听的环境中工作.谁能想到一种方法可以暂时解决此错误,并在没有幂函数或运算符的情况下计算a ^ b(两个浮点数)?

Currently I have to work in an environment where the power-operator is bugged. Can anyone think of a method temporarily work around this bug and compute a^b (both floating point) without a power function or operator?

推荐答案

如果有sqrt()可用:

if you have sqrt() available:

double sqr( double x ) { return x * x; } // meaning of 'precision': the returned answer should be base^x, where // x is in [power-precision/2,power+precision/2] double mypow( double base, double power, double precision ) { if ( power < 0 ) return 1 / mypow( base, -power, precision ); if ( power >= 10 ) return sqr( mypow( base, power/2, precision/2 ) ); if ( power >= 1 ) return base * mypow( base, power-1, precision ); if ( precision >= 1 ) return sqrt( base ); return sqrt( mypow( base, power*2, precision*2 ) ); } double mypow( double base, double power ) { return mypow( base, power, .000001 ); }

测试代码:

void main() { cout.precision( 12 ); cout << mypow( 2.7, 1.23456 ) << endl; cout << pow ( 2.7, 1.23456 ) << endl; cout << mypow( 1.001, 1000.7 ) << endl; cout << pow ( 1.001, 1000.7 ) << endl; cout << mypow( .3, -10.7 ) << endl; cout << pow ( .3, -10.7 ) << endl; cout << mypow( 100000, .00001 ) << endl; cout << pow ( 100000, .00001 ) << endl; cout << mypow( 100000, .0000001 ) << endl; cout << pow ( 100000, .0000001 ) << endl; }

输出:

3.40835049344 3.40835206431 2.71882549461 2.71882549383 393371.348073 393371.212573 1.00011529225 1.00011513588 1.00000548981 1.00000115129

更多推荐

无幂函数的浮点数求幂

本文发布于:2023-11-29 21:57:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647738.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   浮点数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!