ExcelHome技术论坛

 找回密码
 免费注册

QQ登录

只需一步,快速开始

快捷登录

搜索
EH技术汇-专业的职场技能充电站 妙哉!函数段子手趣味讲函数 Excel服务器-会Excel,做管理系统 Excel Home精品图文教程库
HR薪酬管理数字化实战 Excel 2021函数公式学习大典 Excel数据透视表实战秘技 打造核心竞争力的职场宝典
300集Office 2010微视频教程 数据工作者的案头书 免费直播课集锦 ExcelHome出品 - VBA代码宝免费下载
用ChatGPT与VBA一键搞定Excel WPS表格从入门到精通 Excel VBA经典代码实践指南
查看: 2882|回复: 1

快速的BigInteger类,比.Net4自带的要快多了。计算根号2的10W位数字,只需要2.54秒。

[复制链接]

TA的精华主题

TA的得分主题

发表于 2013-12-1 14:53 | 显示全部楼层 |阅读模式
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用  · 内置多项VBA编程加强工具       ★ 免费下载 ★      ★使用手册
本帖最后由 liucqa 于 2013-12-1 15:33 编辑

计算根号2的10W位数字,只需要2.54秒。
1.JPG

调用代码参考如下:
  1.         public static object XLLSqrtBA(string Param1,int CustomScale)
  2.         {
  3.             //判断是不是符合数字要求
  4.             if (!isNumeric(Param1)) return (object)ExcelError.ExcelErrorValue;
  5.             if (Param1.StartsWith("-")) return (object)ExcelError.ExcelErrorValue;

  6.             int decimalpartlength = 0;

  7.             //检查被除数小数部分长度
  8.             int point = Param1.IndexOf('.');
  9.             int pointAdjust = 0;
  10.             if (point >= 0)
  11.             {
  12.                 decimalpartlength = Param1.Length - point - 1;                                        //得到小数部分长度
  13.                 if (!((decimalpartlength & 1) == 0))
  14.                 {
  15.                     pointAdjust = 1;
  16.                 }
  17.             }
  18.             Param1 = Param1.Replace(".", "");       //去掉小数点,等于放大了decimalpartlength次幂

  19.             string input = Param1 + new string('0', 2 * CustomScale + pointAdjust);   //再放大小数位的精度,放大倍数是精度*2   (平方根)
  20.             Skyiv.Numeric.BigInteger ba1 = Skyiv.Numeric.BigInteger.Parse(input);
  21.             Skyiv.Numeric.BigInteger ba2 = Skyiv.Numeric.BigInteger.Sqrt(ba1);
  22.             string result = ba2.ToString();

  23.             int rightpos = (decimalpartlength + pointAdjust) / 2 + CustomScale;
  24.             result = result.Insert(result.Length - rightpos, ".");
  25.             //超出精度截断
  26.             if (rightpos > CustomScale) result = result.Substring(0, result.Length - (rightpos - CustomScale));
  27.             return result;
  28.         }
复制代码
代码使用了Skyiv.Numeric开源库,下载地址 https://bitbucket.org/ben.skyiv/biginteger,顺便说一下,俺调用的是这个库的快速傅立叶变换的那个BigInteger类,而快速傅立叶变换对小规模数据的效率一般,不过由于数据规模小,即使效率一般对整体性能的影响也不大,可以接受。

加载宏下载:
TestXllFunction.rar (936.62 KB, 下载次数: 34)

打包后的函数执行速度会慢50%,在我的机器上如下:
2.JPG

具体原因就不解释了。


最后总结:
通过对BigDecimal的研究,俺学会了操作符重载和VS的单元测试、性能分析等,这是最大的收获







TA的精华主题

TA的得分主题

发表于 2014-3-28 23:39 | 显示全部楼层
您需要登录后才可以回帖 登录 | 免费注册

本版积分规则

手机版|关于我们|联系我们|ExcelHome

GMT+8, 2024-5-13 12:06 , Processed in 0.034837 second(s), 12 queries , Gzip On, MemCache On.

Powered by Discuz! X3.4

© 1999-2023 Wooffice Inc.

沪公网安备 31011702000001号 沪ICP备11019229号-2

本论坛言论纯属发表者个人意见,任何违反国家相关法律的言论,本站将协助国家相关部门追究发言者责任!     本站特聘法律顾问:李志群律师

快速回复 返回顶部 返回列表