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反射机制
    Java基础——Java常用类
    Java基础——多线程
    Java基础——IO流--转换流、标准输入输出流
    Java基础——IO流
    Java基础——枚举与注解
    Java基础——泛型
    codeforces B. Bear and Strings 解题报告
    codeforces A. Black-and-White Cube 解题报告
    codeforces B. Ping-Pong (Easy Version) 解题报告
  • 原文地址:https://www.cnblogs.com/zhanxiage1994/p/6992540.html
Copyright © 2011-2022 走看看