• [C++] log函数的一点小问题


    log函数的一点小问题

    在cppreference中

    	#include<cmath>
    	float log( float arg );	
    	double log( double arg );
    	long double log( long double arg );
    	double log( Integral arg );
    

    1-3) Computes the the natural (base e) logarithm of arg.
    4) A set of overloads or a function template accepting an argument of any integral type. Equivalent to 2) (the argument is cast to double).

    	#include<math.h>
    	float logf( float arg );
    	double log( double arg );
    	long double logl( long double arg );
    	#define log( arg )
    
    

    1-3) Computes the natural (base e) logarithm of arg.
    4) Type-generic macro: If arg has type long double, logl is called. Otherwise, if arg has integer type or the type double, log is called. Otherwise, logf is called. If arg is complex or imaginary, then the macro invokes the corresponding complex function (clogf, clog, clogl).

    在刷leetcode的Power of Three时,一直A不过去,转到VS中debug了一下,发现问题了。

    Given an integer, write a function to determine if it is a power of three.
    
    A不过去的代码是
        bool isPowerOfThree(int n) {
            if(n <= 0) return false;
            return n == pow(3,int(log(n)/log(3)));
        }
    能A过去的代码是
        bool isPowerOfThree(int n) {
            if(n <= 0) return false;
            return n == pow(3,int(logf(n)/logf(3)));
        }
    

    发现区别了么?
    loglogf上,计算精度的问题。

    但是在紧接着的下一题Power of Two时,提交上一题能A的代码又过不去了,但是上一题不能A过去的代码能A过去了。
    搞的我有点懵圈啊。

    为了避免此问题精度问题,在使用对数函数是,尽量使用log10

  • 相关阅读:
    浅谈js的继承
    Android调用jni全过程,方便以后操作
    oracle中查找执行效率低下的SQL
    EBS R12 怎么修改APPS密码
    oracle查看系统资源占用情况
    ramfs
    091104 晴
    周六
    注意调整
    短信收到
  • 原文地址:https://www.cnblogs.com/zhanxiage1994/p/6992540.html
Copyright © 2020-2023  润新知