我一直在寻找用于计算的有效方法b(说a = 2和b = 50).为了开始,我决定看一下Math.Pow()函数的实现.但在.NET Reflector中,我发现的只有:
[MethodImpl(MethodImplOptions.InternalCall), SecuritySafeCritical]
public static extern double Pow(double x, double y);
Run Code Online (Sandbox Code Playgroud)
当我调用Math.Pow()函数时,我可以看到内部发生了什么的一些资源?
我正在用C编写一个小型8位微控制器的软件.部分代码是读取电流互感器(ZCT)的ADC值,然后计算RMS值.流过ZCT的电流是正弦曲线但可能会失真.我的代码如下:
float adc_value, inst_current;
float acc_load_current; // accumulator = (I1*I1 + I2*I2 + ... + In*In)
double rms_current;
// Calculate the real instantanous value from the ADC reading
inst_current = (adc_value/1024)*2.5; // 10bit ADC, Voltage ref. 2.5V, so formula is: x=(adc/1024)*2.5V
// Update the RMS value with the new instananous value:
// Substract 1 sample from the accumulator (sample size is 512, so divide accumulator by 512 and substract it from the accumulator)
acc_load_current -= (acc_load_current / 512);
inst_current *= …Run Code Online (Sandbox Code Playgroud) 我不确定平方的幂是否可以处理负指数。我实现了以下仅适用于正数的代码。
#include <stdio.h>
int powe(int x, int exp)
{
if (x == 0)
return 1;
if (x == 1)
return x;
if (x&1)
return powe(x*x, exp/2);
else
return x*powe(x*x, (exp-1)/2);
}
Run Code Online (Sandbox Code Playgroud)
查看https://en.wikipedia.org/wiki/Exponentiation_by_squaring没有帮助,因为以下代码似乎是错误的。
Function exp-by-squaring(x, n )
if n < 0 then return exp-by-squaring(1 / x, - n );
else if n = 0 then return 1;
else if n = 1 then return x ;
else if n is even then return exp-by-squaring(x * x, n / 2); …Run Code Online (Sandbox Code Playgroud) 大多数现代语言中的指数很容易..我用我选择的语言中的常用运算符或任何补偿它以获得所需功能的函数.
我想知道,这究竟是如何运作的?
C中的以下算法通常用于演示此效果.
double exp(val, pow) {
for(int i = 0; i < pow; ++i)
val *= val;
return val;
} // exp(2, 3) -> 8
Run Code Online (Sandbox Code Playgroud)
然而,这里有一个严重的错误..如果pow是2.6怎么办?那也会返回8 ..
那只是因为循环条件只比较两个数字..
但是当我做这样的事情时,它运作良好..
#include <math.h>
int main() {
printf("The result of 2 to the power of 2.6 is %.2f", pow(2, 2.6));
}
Run Code Online (Sandbox Code Playgroud)
如何实现后一种行为?
根据答案,似乎泰勒扩展算法是取幂的关键,那么......乘法呢?如何实现十进制乘法?
有没有其他方法可以Math.sqrt()用来获得未知值的平方根?
例如:
var random = (Math.random() * (999 - 1)) + 1;
var sqrt = Math.sqrt(random);
Run Code Online (Sandbox Code Playgroud)
我听说使用Math.sqrt()得到数字的平方根是一个非常慢的操作,我只是想知道是否有更快的方法可以得到随机数的平方根.任何有关这方面的帮助将不胜感激.