标签归档:programming-languages

在Python中显示带有两位小数的浮点数

问题:在Python中显示带有两位小数的浮点数

我有一个带浮点参数的函数(通常是整数或具有一位有效数字的十进制数),我需要在字符串中输出具有两位小数位的值(5-> 5.00、5.5-> 5.50等)。如何在Python中做到这一点?

I have a function taking float arguments (generally integers or decimals with one significant digit), and I need to output the values in a string with two decimal places (5 -> 5.00, 5.5 -> 5.50, etc). How can I do this in Python?


回答 0

您可以为此使用字符串格式运算符:

>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'

运算符的结果是一个字符串,因此您可以将其存储在变量中,进行打印等。

You could use the string formatting operator for that:

>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'

The result of the operator is a string, so you can store it in a variable, print etc.


回答 1

由于这篇文章可能会在这里出现一段时间,因此我们还要指出python 3语法:

"{:.2f}".format(5)

Since this post might be here for a while, lets also point out python 3 syntax:

"{:.2f}".format(5)

回答 2

f字符串格式:

这是Python 3.6中的新功能-照常将字符串放在引号中,并f'...以与r'...原始字符串相同的方式加上前缀。然后,将任何要放入字符串,变量,数字,大括号内的内容放入其中-Python会f'some string text with a {variable} or {number} within that text'像以前的字符串格式化方法那样进行求值,只是该方法更具可读性。

>>> a = 3.141592
>>> print(f'My number is {a:.2f} - look at the nice rounding!')

My number is 3.14 - look at the nice rounding!

您可以在此示例中看到,我们以与以前的字符串格式化方法相似的方式用小数位格式化。

NB a可以是数字,变量甚至是表达式,例如f'{3*my_func(3.14):02f}'

展望未来,使用新代码,我更喜欢f字符串而不是常见的%s或str.format()方法,因为f字符串可以更容易阅读,并且通常更快

f-string formatting:

This was new in Python 3.6 – the string is placed in quotation marks as usual, prepended with f'... in the same way you would r'... for a raw string. Then you place whatever you want to put within your string, variables, numbers, inside braces f'some string text with a {variable} or {number} within that text' – and Python evaluates as with previous string formatting methods, except that this method is much more readable.

>>> foobar = 3.141592
>>> print(f'My number is {foobar:.2f} - look at the nice rounding!')

My number is 3.14 - look at the nice rounding!

You can see in this example we format with decimal places in similar fashion to previous string formatting methods.

NB foobar can be an number, variable, or even an expression eg f'{3*my_func(3.14):02f}'.

Going forward, with new code I prefer f-strings over common %s or str.format() methods as f-strings can be far more readable, and are often much faster.


回答 3

字符串格式:

print "%.2f" % 5

String formatting:

print "%.2f" % 5

回答 4

使用python字符串格式。

>>> "%0.2f" % 3
'3.00'

Using python string formatting.

>>> "%0.2f" % 3
'3.00'

回答 5

字符串格式:

a = 6.789809823
print('%.2f' %a)

要么

print ("{0:.2f}".format(a)) 

舍入函数可以使用:

print(round(a, 2))

round()的好处是,我们可以将结果存储到另一个变量中,然后将其用于其他目的。

b = round(a, 2)
print(b)

String Formatting:

a = 6.789809823
print('%.2f' %a)

OR

print ("{0:.2f}".format(a)) 

Round Function can be used:

print(round(a, 2))

Good thing about round() is that, we can store this result to another variable, and then use it for other purposes.

b = round(a, 2)
print(b)

回答 6

最短的Python 3语法:

n = 5
print(f'{n:.2f}')

Shortest Python 3 syntax:

n = 5
print(f'{n:.2f}')

回答 7

如果您实际上想更改数字本身,而不是只显示不同的数字,请使用format()

将其格式化为2位小数:

format(value, '.2f')

例:

>>> format(5.00000, '.2f')
'5.00'

If you actually want to change the number itself instead of only displaying it differently use format()

Format it to 2 decimal places:

format(value, '.2f')

example:

>>> format(5.00000, '.2f')
'5.00'

回答 8

我知道这是一个古老的问题,但我一直在努力寻找答案。这是我想出的:

Python 3:

>>> num_dict = {'num': 0.123, 'num2': 0.127}
>>> "{0[num]:.2f}_{0[num2]:.2f}".format(num_dict) 
0.12_0.13

I know it is an old question, but I was struggling finding the answer myself. Here is what I have come up with:

Python 3:

>>> num_dict = {'num': 0.123, 'num2': 0.127}
>>> "{0[num]:.2f}_{0[num2]:.2f}".format(num_dict) 
0.12_0.13

回答 9

使用Python 3语法:

print('%.2f' % number)

Using Python 3 syntax:

print('%.2f' % number)

回答 10

如果要在调用输入时获得一个小数点后两位数限制的浮点值,

看看这个〜

a = eval(format(float(input()), '.2f'))   # if u feed 3.1415 for 'a'.
print(a)                                  # output 3.14 will be printed.

If you want to get a floating point value with two decimal places limited at the time of calling input,

Check this out ~

a = eval(format(float(input()), '.2f'))   # if u feed 3.1415 for 'a'.
print(a)                                  # output 3.14 will be printed.

为什么要从1970年1月1日开始计算日期?

问题:为什么要从1970年1月1日开始计算日期?

使用date(1970年1月1日)作为时间操纵的默认标准有什么原因吗?我已经在Java和Python中看到了这个标准。我知道这两种语言。还有其他遵循相同标准的流行语言吗?

请描述。

Is there any reason behind using date(January 1st, 1970) as default standard for time manipulation? I have seen this standard in Java as well as in Python. These two languages I am aware of. Are there other popular languages which follows the same standard?

Please describe.


回答 0

这是Unix时间的标准

Unix时间(或POSIX时间)是一种用于描述时间点的系统,时间点定义为自1970年1月1日午夜多点协调世界时(UTC)起经过的秒数,不包括leap秒。

It is the standard of Unix time.

Unix time, or POSIX time, is a system for describing points in time, defined as the number of seconds elapsed since midnight proleptic Coordinated Universal Time (UTC) of January 1, 1970, not counting leap seconds.


回答 1

使用日期(1970年1月1日)作为默认标准

该问题有两个错误的假设:

  • 自1970年以来,计算领域的所有时间跟踪工作都已开始。
  • 这种跟踪是标准的。

两个打时代

从1970年UTC开始并不总是跟踪计算时间。虽然那个时代参考很流行,但几十年来的各种计算环境至少使用了近二十个时代。有些来自其他世纪。范围从0年(零)到2001年。

这里有一些。

公元前1月1日,1月0日

公元1月1日,

1582年10月15日

1601年1月1日

1840年12月31日

1858年11月17日

1899年12月30日

1899年12月31日

1900年1月1日

1904年1月1日

1967年12月31日

1980年1月1日

1980年1月6日

2000年1月1日

2001年1月1日

Unix时代常见,但不占主导地位

1970年初开始流行,可能是因为它被Unix使用。但这绝不是主导。例如:

ISO 8601

假设count-since-epoch正在使用Unix纪元,将给漏洞带来很大的漏洞。对于人类来说,这样的计数是不可能立即解密的,因此在调试和记录日志时,不容易标记出错误或问题。另一个问题是下面解释的粒度不明确。

我强烈建议您将日期时间值序列化为明确的ISO 8601字符串以进行数据交换,而不是将整数count-since-epoch进行序列化:YYYY-MM-DDTHH:MM:SS.SSSZ例如2014-10-14T16:32:41.018Z

什么,自纪元

自计时以来时间跟踪的另一个问题是时间单位,通常至少使用四个级别的分辨率。

using date(January 1st, 1970) as default standard

The Question makes two false assumptions:

  • All time-tracking in computing is done as a count-since-1970.
  • Such tracking is standard.

Two Dozen Epochs

Time in computing is not always tracked from the beginning of 1970 UTC. While that epoch reference is popular, various computing environments over the decades have used at least nearly two dozen epochs. Some are from other centuries. They range from year 0 (zero) to 2001.

Here are a few.

January 0, 1 BC

January 1, AD 1

October 15, 1582

January 1, 1601

December 31, 1840

November 17, 1858

December 30, 1899

December 31, 1899

January 1, 1900

January 1, 1904

December 31, 1967

January 1, 1980

January 6, 1980

January 1, 2000

January 1, 2001

Unix Epoch Common, But Not Dominant

The beginning of 1970 is popular, probably because of its use by Unix. But by no means is that dominant. For example:

  • Countless millions (billions?) of Microsoft Excel & Lotus 1-2-3 documents use January 0, 1900 (December 31, 1899).
  • The world now has over a billion iOS/OS X devices using the Cocoa (NSDate) epoch of 1 January 2001, GMT.
  • The GPS satellite navigation system uses January 6, 1980 while the European alternative Galileo uses 22 August 1999.

ISO 8601

Assuming a count-since-epoch is using the Unix epoch is opening a big vulnerability for bugs. Such a count is impossible for a human to instantly decipher, so errors or issues won’t be easily flagged when debugging and logging. Another problem is the ambiguity of granularity explained below.

I strongly suggest instead serializing date-time values as unambiguous ISO 8601 strings for data interchange rather than an integer count-since-epoch: YYYY-MM-DDTHH:MM:SS.SSSZ such as 2014-10-14T16:32:41.018Z.

Count Of What Since Epoch

Another issue with count-since-epoch time tracking is the time unit, with at least four levels of resolution commonly used.


回答 2

为什么总是1970年1月1日,因为-1970年1月1日通常称为“时代日期”,是Unix计算机的开始时间,该时间戳记为“ 0”。自该日期以来的任何时间都是根据经过的秒数计算的。用简单的话来说…任何日期的时间戳都将是该日期与“ 1970年1月1日”之间的秒数差异。时间戳只是一个整数,它从“ 1970年1月1日午夜”的数字“ 0”开始并继续递增每隔一秒钟传递“ 1”,以将UNIX时间戳转换为可读日期PHP和其他开源语言提供了内置函数。

why its always 1st jan 1970 , Because – ‘1st January 1970’ usually called as “epoch date” is the date when the time started for Unix computers, and that timestamp is marked as ‘0’. Any time since that date is calculated based on the number of seconds elapsed. In simpler words… the timestamp of any date will be difference in seconds between that date and ‘1st January 1970’ The time stamp is just a integer which started from number ‘0’ on ‘Midnight 1st January 1970’ and goes on incrementing by ‘1’ as each second pass For conversion of UNIX timestamps to readable dates PHP and other open source languages provides built in functions.


回答 3

使用date(1970年1月1日)作为时间操纵的标准背后有什么原因吗?

没关系。

Python的time模块 C库。问肯·汤普森(Ken Thompson)为什么他选择那个日期作为一个时代的日期。也许是某人的生日。

Excel使用两个不同的时期。为什么不同版本的excel使用不同的日期?

除了真正的程序员之外,没有其他人会知道为什么做出这些决定。

和…

不要紧,为什么选择的日期。只是。

天文学家使用他们自己的时代日期:http : //en.wikipedia.org/wiki/Epoch_(天文学

为什么?必须选择一个日期来计算数学。任何随机的日期都可以。

过去的日期通常会避免使用负数。

一些更聪明的软件包使用了多功的公历1年。为什么是1年?
在诸如Calendrical Calculations之类的书中给出了一个原因:从数学上讲它稍微简单一些。

但是如果您考虑一下,1/1/1和1/1/1970之间的差异只是1969,这是一个微不足道的数学偏移量。

Is there any reason behind using date(January 1st, 1970) as standard for time manipulation?

No reason that matters.

Python’s time module is the C library. Ask Ken Thompson why he chose that date for an epochal date. Maybe it was someone’s birthday.

Excel uses two different epochs. Any reason why different version of excel use different dates?

Except for the actual programmer, no one else will ever know why those those kinds of decisions were made.

And…

It does not matter why the date was chosen. It just was.

Astronomers use their own epochal date: http://en.wikipedia.org/wiki/Epoch_(astronomy)

Why? A date has to be chosen to make the math work out. Any random date will work.

A date far in the past avoids negative numbers for the general case.

Some of the smarter packages use the proleptic Gregorian year 1. Any reason why year 1?
There’s a reason given in books like Calendrical Calculations: it’s mathematically slightly simpler.

But if you think about it, the difference between 1/1/1 and 1/1/1970 is just 1969, a trivial mathematical offset.


回答 4

1970年1月1日上午00:00:00是POSIX时间的零点。

January 1st, 1970 00:00:00 am is the zero-point of POSIX time.


回答 5

问: “为什么要从1970年1月1日开始计算日期?”

A)它必须尽可能新,但要包含一些过去。很多人也有同样的感觉,很可能没有其他明显的原因。

他们知道如果把它放到过去就太远了,就会构成问题;如果知道将来会带来负面的结果,他们就会知道。由于事件很可能会在未来发生,因此过去无需深入探讨。

注意: 另一方面,玛雅人需要将事件放到过去,因为他们了解很多过去,因此他们进行了长期压延。只是将所有常规现象放在压延机上。

时间戳并非日历,而是一个时代。而且我相信,玛雅人也使用相同的观点进行了长期压延。(这意味着他们非常了解自己与过去没有任何关系,只需要从更大的角度来看待过去)

Q) “Why are dates calculated from January 1st, 1970?”

A) It had to be as recent as possible, yet include some past. There was most likely no significant other reason as a lot of people feel that same way.

They knew it posed a problem if they placed it too far into the past and they knew it gave negative results if it was in the future. There was no need to go deeper in the past as events will most likely take place in the future.

Notes: The mayans, on the other hand, had the need to place events into the past, since the had the knowledge of a lot of past, for which they made a long-term calender. Just to place all the routine phenomena on the calender.

The timestamp was not meant as a calender, it’s an Epoch. And I believe the mayans made their long-term calender using that same perspective. (meaning they knew damn well they didn’t have any relations with the past, they just had the need to see it in a bigger scale)


回答 6

是的,C(及其家人)。这也是Java采取的方法。

Yes, C (and its family). This is where Java took it too.


编译语言与口译语言

问题:编译语言与口译语言

我正在尝试更好地理解它们之间的区别。我在网上找到了很多解释,但是它们倾向于抽象的差异,而不是实际的含义。

我的大部分编程经验都来自CPython(动态的,解释的)和Java(静态的,编译的)。但是,我知道还有其他种类的解释和编译语言。除了可以从以编译语言编写的程序中分发可执行文件这一事实之外,每种类型是否都有优点/缺点?通常,我听到人们争辩说解释语言可以交互使用,但是我相信编译语言也可以具有交互实现,对吗?

I’m trying to get a better understanding of the difference. I’ve found a lot of explanations online, but they tend towards the abstract differences rather than the practical implications.

Most of my programming experiences has been with CPython (dynamic, interpreted), and Java (static, compiled). However, I understand that there are other kinds of interpreted and compiled languages. Aside from the fact that executable files can be distributed from programs written in compiled languages, are there any advantages/disadvantages to each type? Oftentimes, I hear people arguing that interpreted languages can be used interactively, but I believe that compiled languages can have interactive implementations as well, correct?


回答 0

编译语言是一种程序,一旦编译,该程序就会在目标计算机的指令中表示出来。例如,源代码中的加号“ +”操作可以直接转换为机器代码中的“ ADD”指令。

一种解释语言是其中所述指令不被目标机器直接执行,而是读取和执行通过一些其它方案(其通常写入本机机器的语言)。例如,解释器将在运行时识别相同的“ +”操作,然后使用适当的参数调用其自己的“ add(a,b)”函数,然后执行机器代码“ ADD”指令。

您可以使用解释语言或编译语言来做任何事情,反之亦然-它们都是图灵完整的。但是,两者在实现和使用上都有优点和缺点。

我将完全概括(纯粹主义者请原谅!),但是,粗略地讲,这是编译语言的优点:

  • 通过直接使用目标计算机的本机代码来提高性能
  • 在编译阶段进行功能强大的优化的机会

以下是解释语言的优点:

  • 易于实现(编写好的编译器非常困难!)
  • 无需运行编译阶段:可以“即时”直接执行代码
  • 可以更方便地使用动态语言

请注意,诸如字节码编译之类的现代技术增加了一些额外的复杂性-此处发生的是,编译器针对的是“虚拟机”,该“虚拟机”与底层硬件不同。然后可以在以后的阶段再次编译这些虚拟机指令,以获取本机代码(例如,由Java JVM JIT编译器完成)。

A compiled language is one where the program, once compiled, is expressed in the instructions of the target machine. For example, an addition “+” operation in your source code could be translated directly to the “ADD” instruction in machine code.

An interpreted language is one where the instructions are not directly executed by the target machine, but instead read and executed by some other program (which normally is written in the language of the native machine). For example, the same “+” operation would be recognised by the interpreter at run time, which would then call its own “add(a,b)” function with the appropriate arguments, which would then execute the machine code “ADD” instruction.

You can do anything that you can do in an interpreted language in a compiled language and vice-versa – they are both Turing complete. Both however have advantages and disadvantages for implementation and use.

I’m going to completely generalise (purists forgive me!) but, roughly, here are the advantages of compiled languages:

  • Faster performance by directly using the native code of the target machine
  • Opportunity to apply quite powerful optimisations during the compile stage

And here are the advantages of interpreted languages:

  • Easier to implement (writing good compilers is very hard!!)
  • No need to run a compilation stage: can execute code directly “on the fly”
  • Can be more convenient for dynamic languages

Note that modern techniques such as bytecode compilation add some extra complexity – what happens here is that the compiler targets a “virtual machine” which is not the same as the underlying hardware. These virtual machine instructions can then be compiled again at a later stage to get native code (e.g. as done by the Java JVM JIT compiler).


回答 1

语言本身既不会编译也不会解释,而仅是语言的特定实现。Java是一个完美的例子。有一个基于字节码的平台(JVM),一个本机编译器(gcj)和一个Java超集的插入器(bsh)。那么,Java现在是什么?字节码编译,本机编译还是解释?

Scala,Haskell或Ocaml是经过编译和解释的其他语言。这些语言中的每一种都有一个交互式解释器,以及用于字节码或本机代码的编译器。

因此,通常通过“编译”和“解释”对语言进行分类没有多大意义。

A language itself is neither compiled nor interpreted, only a specific implementation of a language is. Java is a perfect example. There is a bytecode-based platform (the JVM), a native compiler (gcj) and an interpeter for a superset of Java (bsh). So what is Java now? Bytecode-compiled, native-compiled or interpreted?

Other languages, which are compiled as well as interpreted, are Scala, Haskell or Ocaml. Each of these languages has an interactive interpreter, as well as a compiler to byte-code or native machine code.

So generally categorizing languages by “compiled” and “interpreted” doesn’t make much sense.


回答 2

开始思考:过去的爆炸

很久很久以前,曾经有计算解释器和编译器。各种大惊小怪的结果使一个人的优胜劣汰。普遍的观点在当时是沿着线的东西:

  • 口译员:快速开发(编辑和运行)。执行速度很慢,因为每个语句每次执行时都必须将其解释为机器代码(想想这对于执行数千次循环意味着什么)。
  • 编译器:开发缓慢(编辑,编译,链接和运行。编译/链接步骤可能需要花费大量时间)。快速执行。整个程序已经在本机代码中。

在解释的程序和编译的程序之间存在一个或两个数量级的运行时性能差异。其他区别点,例如代码的运行时可变性,也引起了一些关注,但主要区别在于运行时性能问题。

如今,景观已发展到某种程度,以至于汇编/解释的区别几乎是无关紧要的。许多编译语言要求运行时服务不是完全基于机器代码的。而且,大多数解释语言在执行之前都会被“编译”为字节码。字节码解释器可能非常高效,并且从执行速度的角度来看,可以与某些编译器生成的代码相媲美。

经典的区别是,编译器使用某种运行时系统生成本机代码,解释器读取源代码并动态生成代码。如今,几乎没有经典的解释器了-几乎所有经典的解释器都编译成字节码(或其他半编译状态),然后在虚拟“机器”上运行。

Start thinking in terms of a: blast from the past

Once upon a time, long long ago, there lived in the land of computing interpreters and compilers. All kinds of fuss ensued over the merits of one over the other. The general opinion at that time was something along the lines of:

  • Interpreter: Fast to develop (edit and run). Slow to execute because each statement had to be interpreted into machine code every time it was executed (think of what this meant for a loop executed thousands of times).
  • Compiler: Slow to develop (edit, compile, link and run. The compile/link steps could take serious time). Fast to execute. The whole program was already in native machine code.

A one or two order of magnitude difference in the runtime performance existed between an interpreted program and a compiled program. Other distinguishing points, run-time mutability of the code for example, were also of some interest but the major distinction revolved around the run-time performance issues.

Today the landscape has evolved to such an extent that the compiled/interpreted distinction is pretty much irrelevant. Many compiled languages call upon run-time services that are not completely machine code based. Also, most interpreted languages are “compiled” into byte-code before execution. Byte-code interpreters can be very efficient and rival some compiler generated code from an execution speed point of view.

The classic difference is that compilers generated native machine code, interpreters read source code and generated machine code on the fly using some sort of run-time system. Today there are very few classic interpreters left – almost all of them compile into byte-code (or some other semi-compiled state) which then runs on a virtual “machine”.


回答 3

极端简单的情况:

  • 编译器将生成目标计算机的本机可执行文件格式的二进制可执行文件。该二进制文件包含除系统库以外的所有必需资源。它无需任何准备和处理即可运行,并且像闪电一样运行,因为该代码是目标计算机上CPU的本机代码。

  • 解释器将在循环中向用户显示提示,用户可以在其中输入语句或代码,并且在命中RUN或等效命令时,解释器将检查,扫描,解析并以解释方式执行每一行,直到程序运行至停止点或错误为止。因为每一行都是独立处理的,并且解释器不会从以前的行中“学到”任何东西,所以每行每次都需要将人类可读的语言转换为机器指令,所以这太慢了。从好的方面来说,用户可以通过各种方式检查程序并与之交互:更改变量,更改代码,在跟踪或调试模式下运行……等等。

顺便说一句,让我解释一下生活不再那么简单了。例如,

  • 许多解释器会预编译给出的代码,因此不必一次又一次地重复翻译步骤。
  • 一些编译器不编译为特定于CPU的机器指令,而是编译为字节码,这是一种虚拟机器的人造机器代码。这使编译后的程序更具可移植性,但是在每个目标系统上都需要一个字节码解释器。
  • 字节码解释器(我现在在这里看着Java)倾向于在执行之前为目标部分的CPU重新编译它们获得的字节码(称为JIT)。为了节省时间,通常只对经常运行的代码(热点)执行此操作。
  • 一些看起来和行为像解释器的系统(例如,Clojure)会立即编译它们获得的任何代码,但允许以交互方式访问程序环境。从根本上来说,这就是二进制编译器为解释器带来的便利。
  • 一些编译器并没有真正编译,只是预消化和压缩代码。我听说前阵子就是Perl的工作方式。因此,有时编译器只是在做一些工作,而且大部分仍在解释中。

最终,如今,解释与编译是一个折衷方案,花费(一次)编译的时间通常会因更好的运行时性能而获得回报,但是解释性环境为交互提供了更多机会。编译与解释主要是关于如何“理解”程序的工作如何在不同的过程之间进行划分的问题,而如今,由于语言和产品试图同时兼顾两者的优势,这条线有些模糊。

The extreme and simple cases:

  • A compiler will produce a binary executable in the target machine’s native executable format. This binary file contains all required resources except for system libraries; it’s ready to run with no further preparation and processing and it runs like lightning because the code is the native code for the CPU on the target machine.

  • An interpreter will present the user with a prompt in a loop where he can enter statements or code, and upon hitting RUN or the equivalent the interpreter will examine, scan, parse and interpretatively execute each line until the program runs to a stopping point or an error. Because each line is treated on its own and the interpreter doesn’t “learn” anything from having seen the line before, the effort of converting human-readable language to machine instructions is incurred every time for every line, so it’s dog slow. On the bright side, the user can inspect and otherwise interact with his program in all kinds of ways: Changing variables, changing code, running in trace or debug modes… whatever.

With those out of the way, let me explain that life ain’t so simple any more. For instance,

  • Many interpreters will pre-compile the code they’re given so the translation step doesn’t have to be repeated again and again.
  • Some compilers compile not to CPU-specific machine instructions but to bytecode, a kind of artificial machine code for a ficticious machine. This makes the compiled program a bit more portable, but requires a bytecode interpreter on every target system.
  • The bytecode interpreters (I’m looking at Java here) recently tend to re-compile the bytecode they get for the CPU of the target section just before execution (called JIT). To save time, this is often only done for code that runs often (hotspots).
  • Some systems that look and act like interpreters (Clojure, for instance) compile any code they get, immediately, but allow interactive access to the program’s environment. That’s basically the convenience of interpreters with the speed of binary compilation.
  • Some compilers don’t really compile, they just pre-digest and compress code. I heard a while back that’s how Perl works. So sometimes the compiler is just doing a bit of the work and most of it is still interpretation.

In the end, these days, interpreting vs. compiling is a trade-off, with time spent (once) compiling often being rewarded by better runtime performance, but an interpretative environment giving more opportunities for interaction. Compiling vs. interpreting is mostly a matter of how the work of “understanding” the program is divided up between different processes, and the line is a bit blurry these days as languages and products try to offer the best of both worlds.


回答 4

来自http://www.quora.com/What-is-the-difference-between-compiled-and-interpreted-programming-languages

这没有什么区别,因为“编译程序设计语言”和“解释程序设计语言”不是有意义的概念。任何编程语言(实际上是任何一种编程语言)都可以解释或编译。因此,解释和编译是实现技术,而不是语言的属性。

解释是一种技术,通过该技术,另一个程序(解释器)代表正在解释的程序执行操作以使其运行。如果您可以想象阅读程序并按照程序说的做一步一步,例如在草稿纸上说,那也是解释器的工作。解释程序的常见原因是解释器相对容易编写。另一个原因是,解释器可以监视程序在运行时试图执行的操作,以执行安全性策略。

编译是一种技术,通过该技术可以将用一种语言(“源语言”)编写的程序转换为另一种语言(“目标语言”)的程序,这希望与原始程序具有相同的含义。在进行翻译时,编译器通常还会尝试以使目标程序更快的方式(不改变其含义!)对程序进行转换。编译程序的一个常见原因是,有一种很好的方法可以以目标语言快速运行程序,而无需一路解释源语言。

根据上述定义,您可能已经猜到这两种实现技术不是互斥的,甚至可能是互补的。传统上,编译器的目标语言是机器代码或类似的东西,它表示特定计算机CPU可以理解的任何数量的编程语言。然后,机器代码将“运行在金属上”(尽管如果看起来足够接近,人们可能会发现“金属”的工作原理很像解释器)。但是,如今,使用编译器生成要解释的目标代码已经非常普遍了,例如,Java曾经(有时仍然这样做)就是这种方式。有些编译器会将其他语言翻译成JavaScript,然后通常在网络浏览器中运行,这些浏览器可能会解释JavaScript,或将其编译为虚拟机或本机代码。我们还提供了机器码解释器,可用于在另一种机器上模拟一种硬件。或者,可以使用编译器生成目标代码,然后该目标代码将成为另一编译器的源代码,后者甚至可以及时在内存中编译代码以使其运行,然后依次运行。。。你明白了。有很多方法可以组合这些概念。

From http://www.quora.com/What-is-the-difference-between-compiled-and-interpreted-programming-languages

There is no difference, because “compiled programming language” and “interpreted programming language” aren’t meaningful concepts. Any programming language, and I really mean any, can be interpreted or compiled. Thus, interpretation and compilation are implementation techniques, not attributes of languages.

Interpretation is a technique whereby another program, the interpreter, performs operations on behalf of the program being interpreted in order to run it. If you can imagine reading a program and doing what it says to do step-by-step, say on a piece of scratch paper, that’s just what an interpreter does as well. A common reason to interpret a program is that interpreters are relatively easy to write. Another reason is that an interpreter can monitor what a program tries to do as it runs, to enforce a policy, say, for security.

Compilation is a technique whereby a program written in one language (the “source language”) is translated into a program in another language (the “object language”), which hopefully means the same thing as the original program. While doing the translation, it is common for the compiler to also try to transform the program in ways that will make the object program faster (without changing its meaning!). A common reason to compile a program is that there’s some good way to run programs in the object language quickly and without the overhead of interpreting the source language along the way.

You may have guessed, based on the above definitions, that these two implementation techniques are not mutually exclusive, and may even be complementary. Traditionally, the object language of a compiler was machine code or something similar, which refers to any number of programming languages understood by particular computer CPUs. The machine code would then run “on the metal” (though one might see, if one looks closely enough, that the “metal” works a lot like an interpreter). Today, however, it’s very common to use a compiler to generate object code that is meant to be interpreted—for example, this is how Java used to (and sometimes still does) work. There are compilers that translate other languages to JavaScript, which is then often run in a web browser, which might interpret the JavaScript, or compile it a virtual machine or native code. We also have interpreters for machine code, which can be used to emulate one kind of hardware on another. Or, one might use a compiler to generate object code that is then the source code for another compiler, which might even compile code in memory just in time for it to run, which in turn . . . you get the idea. There are many ways to combine these concepts.


回答 5

与已编译的源代码相比,已解释的源代码的最大优势是PORTABILITY

如果您的源代码已编译,则需要为要在其上运行程序的每种类型的处理器和/或平台编译一个不同的可执行文件(例如,一个用于Windows x86,一个用于Windows x64,一个用于Linux x64,等等。上)。此外,除非您的代码完全符合标准并且不使用任何平台特定的功能/库,否则您实际上将需要编写和维护多个代码库!

如果您的源代码被解释,则只需编写一次即可,并且可以由任何平台上的适当解释器来解释和执行它!它是便携式的!需要注意的是一个解释器本身是一个可执行程序编写和编译为特定平台。

编译后代码的一个优点是,它向最终用户隐藏了源代码(可能是知识产权),因为您部署了晦涩的二进制可执行文件,而不是部署原始的人类可读源代码。

The biggest advantage of interpreted source code over compiled source code is PORTABILITY.

If your source code is compiled, you need to compile a different executable for each type of processor and/or platform that you want your program to run on (e.g. one for Windows x86, one for Windows x64, one for Linux x64, and so on). Furthermore, unless your code is completely standards compliant and does not use any platform-specific functions/libraries, you will actually need to write and maintain multiple code bases!

If your source code is interpreted, you only need to write it once and it can be interpreted and executed by an appropriate interpreter on any platform! It’s portable! Note that an interpreter itself is an executable program that is written and compiled for a specific platform.

An advantage of compiled code is that it hides the source code from the end user (which might be intellectual property) because instead of deploying the original human-readable source code, you deploy an obscure binary executable file.


回答 6

编译器和解释器完成相同的工作:将编程语言翻译为另一种编程语言,通常更接近硬件,通常指导可执行的机器代码。

传统上,“编译”是指这种翻译一次完成,由开发人员完成,然后将生成的可执行文件分发给用户。纯粹的例子:C ++。编译通常花费很长时间,并尝试进行大量昂贵的优化,以使生成的可执行文件运行更快。最终用户没有工具和知识来自己编译东西,并且可执行文件通常必须在各种硬件上运行,因此您不能进行许多针对硬件的优化。在开发过程中,单独的编译步骤意味着更长的反馈周期。

传统上,“已解释”是指当用户要运行程序时,翻译是“即时”进行的。纯粹的例子:香草PHP。天真的解释器每次运行时都必须解析和翻译每段代码,这使其非常慢。它无法进行复杂,成本高昂的优化,因为它们所花费的时间比执行所节省的时间还要长。但是它可以充分利用其运行的硬件的功能。缺少单独的编译步骤可减少开发过程中的反馈时间。

但是如今,“编译与解释”已不是一个黑白问题,介于两者之间。天真的,简单的口译员已经绝迹了。许多语言使用两步过程,其中将高级代码转换为平台无关的字节码(解释起来更快)。然后,您将拥有“及时编译器”,每个程序运行一次最多编译一次代码,有时缓存结果,甚至可以明智地决定解释很少运行的代码,并对运行频繁的代码进行强大的优化。在开发过程中,调试器甚至可以针对传统编译语言在正在运行的程序中切换代码。

A compiler and an interpreter do the same job: translating a programming language to another pgoramming language, usually closer to the hardware, often direct executable machine code.

Traditionally, “compiled” means that this translation happens all in one go, is done by a developer, and the resulting executable is distributed to users. Pure example: C++. Compilation usually takes pretty long and tries to do lots of expensive optmization so that the resulting executable runs faster. End users don’t have the tools and knowledge to compile stuff themselves, and the executable often has to run on a variety of hardware, so you can’t do many hardware-specific optimizations. During development, the separate compilation step means a longer feedback cycle.

Traditionally, “interpreted” means that the translation happens “on the fly”, when the user wants to run the program. Pure example: vanilla PHP. A naive interpreter has to parse and translate every piece of code every time it runs, which makes it very slow. It can’t do complex, costly optimizations because they’d take longer than the time saved in execution. But it can fully use the capabilities of the hardware it runs on. The lack of a separrate compilation step reduces feedback time during development.

But nowadays “compiled vs. interpreted” is not a black-or-white issue, there are shades in between. Naive, simple interpreters are pretty much extinct. Many languages use a two-step process where the high-level code is translated to a platform-independant bytecode (which is much faster to interpret). Then you have “just in time compilers” which compile code at most once per program run, sometimes cache results, and even intelligently decide to interpret code that’s run rarely, and do powerful optimizations for code that runs a lot. During development, debuggers are capable of switching code inside a running program even for traditionally compiled languages.


回答 7

首先,澄清一下,Java不是完全以C ++的方式静态编译和链接的。它被编译成字节码,然后由JVM解释。JVM可以及时对本机语言进行编译,但不必这样做。

更重要的是:我认为互动是主要的实际差异。由于所有内容均已解释,因此您可以摘录一小段代码,然后针对环境的当前状态进行解析和运行。因此,如果您已经执行过初始化变量的代码,则可以访问该变量,等等。它确实可以将其自身用于诸如功能样式之类的事情。

但是,解释会花费很多,尤其是当您拥有一个具有大量引用和上下文的大型系统时。根据定义,这是浪费的,因为可能必须两次解释和优化相同的代码(尽管大多数运行时对此都有一些缓存和优化)。尽管如此,您仍然需要支付运行时成本,并且经常需要运行时环境。您也不太可能看到复杂的过程间优化,因为目前它们的性能还不够互动。

因此,对于那些变化不大的大型系统,对于某些语言而言,预编译和预链接所有内容更有意义,请执行您可以做的所有优化。最终将获得非常精益的运行时,该运行时已针对目标计算机进行了优化。

至于生成可执行文件,与恕我直言无关。您通常可以使用编译语言创建可执行文件。但是,您也可以使用解释语言创建可执行文件,只是解释器和运行时已打包在可执行文件中,并且对您隐藏了。这意味着您通常仍需支付运行时成本(尽管我确信对于某些语言,有一些方法可以将所有内容转换为树可执行文件)。

我不同意所有语言都可以互动。某些语言(例如C)与机器和整个链接结构紧密相关,因此我不确定您是否可以构建有意义的完整交互式版本

First, a clarification, Java is not fully static-compiled and linked in the way C++. It is compiled into bytecode, which is then interpreted by a JVM. The JVM can go and do just-in-time compilation to the native machine language, but doesn’t have to do it.

More to the point: I think interactivity is the main practical difference. Since everything is interpreted, you can take a small excerpt of code, parse and run it against the current state of the environment. Thus, if you had already executed code that initialized a variable, you would have access to that variable, etc. It really lends itself way to things like the functional style.

Interpretation, however, costs a lot, especially when you have a large system with a lot of references and context. By definition, it is wasteful because identical code may have to be interpreted and optimized twice (although most runtimes have some caching and optimizations for that). Still, you pay a runtime cost and often need a runtime environment. You are also less likely to see complex interprocedural optimizations because at present their performance is not sufficiently interactive.

Therefore, for large systems that are not going to change much, and for certain languages, it makes more sense to precompile and prelink everything, do all the optimizations that you can do. This ends up with a very lean runtime that is already optimized for the target machine.

As for generating executbles, that has little to do with it, IMHO. You can often create an executable from a compiled language. But you can also create an executable from an interpreted language, except that the interpreter and runtime is already packaged in the exectuable and hidden from you. This means that you generally still pay the runtime costs (although I am sure that for some language there are ways to translate everything to a tree executable).

I disagree that all languages could be made interactive. Certain languages, like C, are so tied to the machine and the entire link structure that I’m not sure you can build a meaningful fully-fledged interactive version


回答 8

给出实际答案相当困难,因为区别在于语言定义本身。可以为每种编译语言构建解释器,但不可能为每种解释语言构建编译器。语言的形式定义非常重要。从而使理论上的信息学方面的东西更受大学的欢迎。

It’s rather difficult to give a practical answer because the difference is about the language definition itself. It’s possible to build an interpreter for every compiled language, but it’s not possible to build an compiler for every interpreted language. It’s very much about the formal definition of a language. So that theoretical informatics stuff noboby likes at university.


回答 9

Python图书©2015 Imagine Publishing Ltd,仅通过第10页中提到的以下提示来区分差异:

一种解释性语言(例如Python)是一种将源代码转换为机器代码,然后在每次程序运行时执行的语言。这与诸如C之类的编译语言不同,后者仅将源代码转换为机器代码一次-每次程序运行时都会执行生成的机器代码。

The Python Book © 2015 Imagine Publishing Ltd, simply distunguishes the difference by the following hint mentioned in page 10 as:

An interpreted language such as Python is one where the source code is converted to machine code and then executed each time the program runs. This is different from a compiled language such as C, where the source code is only converted to machine code once – the resulting machine code is then executed each time the program runs.


回答 10

编译是从以编译的编程语言编写的代码创建可执行程序的过程。编译允许计算机运行和理解程序,而无需使用用于创建该程序的编程软件。编译程序时,通常是针对特定平台(例如IBM平台)编译的,该平台可与IBM兼容计算机一起使用,但不适用于其他平台(例如Apple平台)。第一个编译器是由Grace Hopper在哈佛Mark I计算机上开发的。今天,大多数高级语言将包括其自己的编译器或可用的工具包,可用于编译程序。与Java一起使用的编译器的一个很好的例子是Eclipse,而与C和C ++一起使用的编译器的一个例子是gcc命令。

Compile is the process of creating an executable program from code written in a compiled programming language. Compiling allows the computer to run and understand the program without the need of the programming software used to create it. When a program is compiled it is often compiled for a specific platform (e.g. IBM platform) that works with IBM compatible computers, but not other platforms (e.g. Apple platform). The first compiler was developed by Grace Hopper while working on the Harvard Mark I computer. Today, most high-level languages will include their own compiler or have toolkits available that can be used to compile the program. A good example of a compiler used with Java is Eclipse and an example of a compiler used with C and C++ is the gcc command. Depending on how big the program is it should take a few seconds or minutes to compile and if no errors are encountered while being compiled an executable file is created.check this information


回答 11

简短(不精确)的定义:

编译语言:整个程序立即转换为机器代码,然后由CPU运行机器代码。

解释的语言:逐行读取程序,一旦读取一行,CPU就会执行该行的机器指令。

但是,实际上,如今只有很少的语言是纯编译的或纯解释的,通常是混合的。有关图片的详细说明,请参见以下线程:

编译和解释之间有什么区别?

或我后来的博客文章:

https://orangejuiceliberationfront.com/the-difference-between-compiler-and-interpreter/

Short (un-precise) definition:

Compiled language: Entire program is translated to machine code at once, then the machine code is run by the CPU.

Interpreted language: Program is read line-by-line and as soon as a line is read the machine instructions for that line are executed by the CPU.

But really, few languages these days are purely compiled or purely interpreted, it often is a mix. For a more detailed description with pictures, see this thread:

What is the difference between compilation and interpretation?

Or my later blog post:

https://orangejuiceliberationfront.com/the-difference-between-compiler-and-interpreter/