zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    十大经典排序算法最强总结(含JAVA代码实现)
    Java相关官方链接
    强网杯2020(Funhash)
    强网杯2020(主动)
    强网杯2020(upload)
    (内存取证)46届世界技能大赛湖北省选拔赛
    (流量分析)46届世界技能大赛湖北省选拔赛
    CISCO ASA远程任意文件读取
    OOALV 分割屏幕
    Process Doppelg&#228;nging
  • 原文地址:https://www.cnblogs.com/zhanxiage1994/p/6992540.html
Copyright © 2011-2022 走看看