提高C ++与Python的竞争力 [英] Raising to powers in C++ vs. Python

查看:114
本文介绍了提高C ++与Python的竞争力的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自Python,我注意到C ++中的东西往往会更复杂一些。一个很好的例子就是将数字提升到一个权力。在Python的数学库中,所需要的只是:

  a = a ** b 

然而,在C ++中我找到了在线文档的解释,例如.....

  // float 
pow(float base,float exp);
// double
pow(double base,double exp);
// long double
pow(long double base,long double exp);
// float
pow(float base,int iexp);
// double
pow(double base,int iexp);
// long double
pow(long double base,int iexp);
//提升
pow(算术1基础,算术2 exp);

很显然,C ++的创建者一定有这样的理由,但作为一个新的程序员,那些原因没有我。这是否为答案提供了更大的灵活性?从权力的角度来说,我在C ++中给了我什么好处?

解决方案

python中的数字没有限制。由此产生的一些后果是,程序往往会比较慢,因为python不是静态类型的,并且由于它不知道数字是否在一定范围内,所以会产生更多开销。总而言之,以这种方式使用重载函数的主要原因是出于速度的目的,并且更容易推断发生了什么。 Python提供了很多便利,但有时会变得很难推理。其次,大多数语言都有一个math.pow函数(例如Java),虽然它有点冗长,但我认为它仍然很容易理解。请注意,当您使用C ++调用pow()时,编译器会找出哪些pow(某些数据类型,某种数据类型)应该被调用,并且不必担心多个定义。


Coming from Python, I've noticed things in C++ tend to be a little more complicated. A good example would be raising numbers to a power. In Python's math library, all that is needed is:

a = a**b

However, in C++ I've found explanations in online documentation such as.....

//float
pow( float base, float exp );
//double      
pow( double base, double exp );
//long double 
pow( long double base, long double exp );
//float
pow( float base, int iexp );
//double      
pow( double base, int iexp );
//long double 
pow( long double base, int iexp );
//promoted    
pow( Arithmetic1 base, Arithmetic2 exp );

Obviously the creators of C++ must have had great reasons for making it this way, but as a new programmer, those reasons elude me. Does this give greater flexibility over the answer? What benefits have I been given here in C++ in terms of powers?

解决方案

Numbers in python have no limit. Some consequences that arise out of this is that programs tend to be slower since python is not statically typed, and has more overhead since it does not know if a number is within a certain range. In short, the main reason for using overloading functions in that way is for speed purposes, and it's easier to reason about what's happening under the hood. Python provides a lot of conveniences, but sometimes become very difficult to reason about.

Secondly, most languages have a math.pow function (Java also for example), and while it's a bit verbose, I think it's still very easy to understand. Note that when you call pow() in C++, the compiler will figure out which of the pow(some data type, some data type) should be called and there is no need to worry over the multiple definitions.

这篇关于提高C ++与Python的竞争力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆