[issue34311] locale.format() and locale.format_string() cast Decimals to float

2021-04-12 Thread Stéphane Wirtel

Stéphane Wirtel  added the comment:

I have merged the PR, thank you to Cédric for the PR, and thank you to Steve 
for his review.

--
resolution:  -> fixed
stage: commit review -> resolved
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34311] locale.format() and locale.format_string() cast Decimals to float

2021-04-12 Thread Stéphane Wirtel

Stéphane Wirtel  added the comment:


New changeset e126547c070fbc080562abb08e16a2c93a8a805d by Cédric Krier in 
branch 'master':
bpo-34311: Add locale.localize (GH-15275)
https://github.com/python/cpython/commit/e126547c070fbc080562abb08e16a2c93a8a805d


--
nosy: +matrixise

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34311] locale.format() and locale.format_string() cast Decimals to float

2021-04-12 Thread Stéphane Wirtel

Change by Stéphane Wirtel :


--
versions: +Python 3.10 -Python 3.8

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue41719] Why does not range() support decimals?

2020-09-11 Thread chen-y0y0


Change by chen-y0y0 :


--
resolution:  -> not a bug
stage: needs patch -> resolved
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue41719] Why does not range() support decimals?

2020-09-04 Thread Raymond Hettinger


Raymond Hettinger  added the comment:

FWIW, the usual approach to the OP's problem is:

>>> [x*0.5 for x in range(10)]
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]

This technique generalizes to other sequences as well:

>>> [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

As Steven points out, numeric work typically requires something different and a 
bit more sophisticated.  The numpy package may be your best bet for this kind 
of work.

--
nosy: +rhettinger

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue41719] Why does not range() support decimals?

2020-09-04 Thread Steven D'Aprano


Steven D'Aprano  added the comment:

Generating a range of equally-spaced floats is tricky and the range builtin is 
not the right solution for this.

For numerical work, we often need to specify the number of steps, not the step 
size. For instance, in numeric integration, we often like to double the number 
of steps and avoid re-calculation.

We often need to skip either the start or end point, or both, or neither.

If you specify the step size, as range does, you can have off-by-one errors due 
to float rounding.

See here for a discussion and possible solution:

https://code.activestate.com/recipes/577878

--
nosy: +steven.daprano

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue41719] Why does not range() support decimals?

2020-09-04 Thread Terry J. Reedy


Terry J. Reedy  added the comment:

The original title was "Why does not range() support decimals?".  In general, 
such questions should be directed to question forums, such as 
https://mail.python.org/mailman/listinfo/python-list or stackoverflow.com.

This question has been answered on both, with alternatives, in particular on
https://stackoverflow.com/questions/477486/how-to-use-a-decimal-range-step-value
https://stackoverflow.com/questions/12403411/range-with-float-step-argument
and other duplicates.

I am leaving this open to add this frequent question to our FAQ, in particular 
at
https://docs.python.org/3/faq/programming.html#sequences-tuples-lists
with 'range' added.

This answer should include how to use range to get what people generally want.

--
assignee:  -> docs@python
components: +Documentation -Argument Clinic
nosy: +docs@python, terry.reedy
stage:  -> needs patch
type: compile error -> 
versions: +Python 3.10, Python 3.9 -Python 3.5, Python 3.6, Python 3.7

___
Python tracker 
<https://bugs.python.org/issue41719>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue41719] Why does not range() support decimals?

2020-09-04 Thread chen-y0y0


New submission from chen-y0y0 :

# I try:
>>> range(0,5,0.5)
# I hope it will (0.0,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5). But...
Traceback (most recent call last):
  File "", line 1, in 
range(0,5,0.5)
TypeError: 'float' object cannot be interpreted as an integer

--
components: Argument Clinic
messages: 376378
nosy: larry, prasechen
priority: normal
severity: normal
status: open
title: Why does not range() support decimals?
type: compile error
versions: Python 3.5, Python 3.6, Python 3.7, Python 3.8

___
Python tracker 
<https://bugs.python.org/issue41719>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34311] locale.format() and locale.format_string() cast Decimals to float

2020-01-11 Thread Steve Holden


Steve Holden  added the comment:

Verified. Methododology:

1. Copied test_localise.py from the PR into a master checkout.
2. Added a null locale.localize.
3. Verified that all new tests failed.

.. code-block::

  Ran 64 tests in 0.023s

  FAILED (errors=4, skipped=4)
  (base) blockhead:cpython sholden$ vi Lib/locale.py
  (base) blockhead:cpython sholden$ ./python.exe -m test.test_locale
  ...F...testing with ('tr_TR', 
'ISO8859-9') .testing with 'en_US.UTF-8'... .testing with 'en_US.UTF-8'... 
.testing with 'en_US.UTF-8'... .testing with 'en_US.UTF-8'... .testing with 
'en_US.UTF-8'... .testing with 'en_US.UTF-8'... .testing with 'en_US.UTF-8'... 
.testing with 'en_US.UTF-8'... F
  ==
  FAIL: test_localize_invalid_format (__main__.TestEnUSLocalize)
  --
  Traceback (most recent call last):
File "/Users/sholden/cpython/Lib/test/test_locale.py", line 613, in 
test_localize_invalid_format
  locale.localize('foo')
  AssertionError: ValueError not raised

  ==
  FAIL: test_localize (__main__.TestfrFRLocalize)
  --
  Traceback (most recent call last):
File "/Users/sholden/cpython/Lib/test/test_locale.py", line 625, in 
test_localize
  self._test_localize('5.00', '5,00')
File "/Users/sholden/cpython/Lib/test/test_locale.py", line 601, in 
_test_localize
  self.assertEqual(locale.localize(value, grouping=grouping), out)
  AssertionError: '5.00' != '5,00'
  - 5.00
  ?  ^
  + 5,00
  ?  ^


  --
  Ran 64 tests in 0.024s

  FAILED (failures=2, skipped=4)

4. Checked out cedk/locale_format branch.
5. Observed that all locale tests now pass.

Seems to me like this one should be good to go, so I've changed the stage to 
"commit review" and await the application of some core developer's commit bit.

--
nosy: +holdenweb
stage: patch review -> commit review

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34311] locale.format() and locale.format_string() cast Decimals to float

2020-01-10 Thread Cédric Krier

Cédric Krier  added the comment:

For me, the name was natural as it is the reverse operation of the existing 
delocalize method.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34311] locale.format() and locale.format_string() cast Decimals to float

2020-01-09 Thread Inada Naoki


Inada Naoki  added the comment:

Does the name "locale.localize" have some origin?

I feel the name doesn't represent well about it is for formatting numeric based 
on LC_NUMERIC.

--
nosy: +inada.naoki

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-09-11 Thread Julien Palard


Change by Julien Palard :


--
resolution:  -> fixed
stage: patch review -> resolved
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-09-11 Thread Julien Palard


Julien Palard  added the comment:


New changeset 629f1f87e9b0bfd9f1dc3d02f966decde5c65201 by Julien Palard (Miss 
Islington (bot)) in branch '3.8':
bpo-23460: Fix documentation for decimal string :g formatting (GH-11850) 
(GH-15954)
https://github.com/python/cpython/commit/629f1f87e9b0bfd9f1dc3d02f966decde5c65201


--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-09-11 Thread miss-islington


Change by miss-islington :


--
pull_requests: +15589
pull_request: https://github.com/python/cpython/pull/15954

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-09-11 Thread Julien Palard


Julien Palard  added the comment:


New changeset 1660a61a105bcd62e2dfa77885959a8992e9f14e by Julien Palard 
(Brennan D Baraban) in branch 'master':
bpo-23460: Fix documentation for decimal string :g formatting (GH-11850)
https://github.com/python/cpython/commit/1660a61a105bcd62e2dfa77885959a8992e9f14e


--
nosy: +mdk

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue38024] adding or subtracting decimals

2019-09-04 Thread Serhiy Storchaka


Change by Serhiy Storchaka :


--
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue38024] adding or subtracting decimals

2019-09-04 Thread Karthikeyan Singaravelan


Karthikeyan Singaravelan  added the comment:

Please include the text of the repl session in issue so that it would be easy 
to copy past and also more accessible. The issue is as below in the attached 
image. I guess this is due to floating point representation and has some 
possible solutions in this page : 
https://docs.python.org/3/tutorial/floatingpoint.html and 
https://docs.python.org/3/faq/design.html#why-are-floating-point-calculations-so-inaccurate

$ python3
Python 3.8.0b4 (v3.8.0b4:d93605de72, Aug 29 2019, 21:47:47)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 17.5 + 6169.90760
6186.90764999
>>> from decimal import Decimal
>>> Decimal('17.5') + Decimal('6169.90760')
Decimal('6186.90765')

--
nosy: +xtreak

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue38024] adding or subtracting decimals

2019-09-04 Thread QA.Nathaniel Logarta


New submission from QA.Nathaniel Logarta 
:

Just try to add decimals
It doesn't have any trigger on my end
As long as it is a complex decimal or adding decimal zeroes to non-zero

--
components: Windows
files: adding or subtracting decimals.PNG
messages: 351117
nosy: QA.Nathaniel Logarta, paul.moore, steve.dower, tim.golden, zach.ware
priority: normal
severity: normal
status: open
title: adding or subtracting decimals
versions: Python 3.7
Added file: https://bugs.python.org/file48590/adding or subtracting decimals.PNG

___
Python tracker 
<https://bugs.python.org/issue38024>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34311] locale.format() and locale.format_string() cast Decimals to float

2019-08-14 Thread Cédric Krier

Cédric Krier  added the comment:

I think we can solve this issue like I solved issue13918 by providing a 
locale.localize() method which does the formatting as locale.format_string does 
but using the already formatted string.

I created PR-15275 which implements it and also use the new format in 
locale.currency as it is highly probable that currency will be used with 
Decimal.

--
nosy: +ced

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34311] locale.format() and locale.format_string() cast Decimals to float

2019-08-14 Thread Cédric Krier

Change by Cédric Krier :


--
pull_requests: +14997
pull_request: https://github.com/python/cpython/pull/15275

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-03-03 Thread Brennan D Baraban


Brennan D Baraban <3...@holbertonschool.com> added the comment:

Hi Stefan. Is there an update you would like me to make on this PR? Otherwise, 
pinging for review.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-02-24 Thread Stefan Krah


Stefan Krah  added the comment:

On the other hand, the docs say "insignificant trailing zeros are removed from 
the significand", so technically it *is* correct, because trailing zeros are 
significant in decimal.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-02-24 Thread Stefan Krah


Stefan Krah  added the comment:

I just noticed that there are other differences, for example the "removal of 
trailing zeros" passage does not apply to Decimal:

>>> format(Decimal("1.00e-6"), "g")
'0.0100'

Perhaps it would be easier to have separate docs for float and decimal after 
all, or a long footnote for decimal.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-02-13 Thread Brennan D Baraban


Brennan D Baraban <3...@holbertonschool.com> added the comment:

I submitted a PR just now. I only pushed the change to `string.rst`, as per 
Stefan Krah's suggestion.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-02-13 Thread Brennan D Baraban


Change by Brennan D Baraban <3...@holbertonschool.com>:


--
pull_requests: +11881
stage: needs patch -> patch review

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-02-11 Thread Brennan D Baraban


Brennan D Baraban <3...@holbertonschool.com> added the comment:

Well, Tuomas, I defer submission of a PR to you, as its your original patch.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-02-11 Thread Stefan Krah


Stefan Krah  added the comment:

Yes, these days PRs are the only way to get anything done. Before
GitHub it would have been possible to just commit the small diff
directly to master.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-02-11 Thread Karthikeyan Singaravelan


Karthikeyan Singaravelan  added the comment:

> If contributions are accepted as GitHub pull requests
these days, I can do it myself too.

GitHub pull requests are accepted. Please see https://devguide.python.org/ .

Thanks

--
nosy: +xtreak

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-02-11 Thread Stefan Krah


Stefan Krah  added the comment:

The patch LGTM, but I'm not sure if we need to document __format__().
Personally I probably wouldn't.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-02-11 Thread Tuomas Suutari


Tuomas Suutari  added the comment:

> What is the status of this issue? I can submit a PR based on Tuomas Suutari's 
> patch.

Don't know more about the status, but nobody seemed to care to take my
patch forward. If contributions are accepted as GitHub pull requests
these days, I can do it myself too.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2019-02-10 Thread Brennan D Baraban


Brennan D Baraban <3...@holbertonschool.com> added the comment:

What is the status of this issue? I can submit a PR based on Tuomas Suutari's 
patch.

--
nosy: +bdbaraban

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2018-10-24 Thread Sergey Fedoseev


Change by Sergey Fedoseev :


--
nosy: +sir-sigurd

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2018-09-02 Thread Lorenz Mende


Lorenz Mende  added the comment:

I want to bring this issue up again.
As the others correctly stated, either the documentation or the implementation 
of Decimal 'g' formatting is incorrect.

For floats the implementation suits the docu:
>>> '{:g}'.format(0.1)
'1e-05'
For decimals:
>>> '{:g}'.format(decimal.Decimal('0.1'))
'0.1'

As there is a deviation between documentation and implementation, I advise to 
modify one of both.

--
nosy: +LorenzMende

___
Python tracker 
<https://bugs.python.org/issue23460>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34311] locale.format() and locale.format_string() cast Decimals to float

2018-08-04 Thread James Emerton


James Emerton  added the comment:

It looks like a bot got a bit excited when I mentioned this issue in the PR for 
bpo-33731. I unlinked the PR but this issue still got flagged for review.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34311] locale.format() and locale.format_string() cast Decimals to float

2018-08-04 Thread James Emerton


Change by James Emerton :


--
pull_requests:  -8166

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34311] locale.format() and locale.format_string() cast Decimals to float

2018-08-04 Thread James Emerton


Change by James Emerton :


--
keywords: +patch
pull_requests: +8166
stage:  -> patch review

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34311] locale.format() and locale.format_string() cast Decimals to float

2018-08-01 Thread James Emerton


James Emerton  added the comment:

Certainly adding another letter to the format spec would solve my issue and 
would in fact be somewhat preferable to using local.format directly.

I think this could be fixed in the locale module by transforming the format 
spec and using new-style formatting, but I'm not familiar enough with the 
corner cases to know if its practical to cover all the possible cases; 
particularly those coming from format_string().

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34311] locale.format() and locale.format_string() cast Decimals to float

2018-08-01 Thread Eric V. Smith


Eric V. Smith  added the comment:

Would my suggestion in #33731 of adding another letter in the format spec for 
float and decimal.Decimal solve your problem? I guess if you're using 
monetary=True you'd need two additional letters: like 'f' but locale aware, and 
like 'f' but locale aware and monetary=True.  Maybe 'l' and 'L' for these? In 
this case, there would be no changes to the locale module.

I don't see any good way of using new-style formatting without changing 
float.__format__ and decimal.Decimal.__format__.

--
components: +Interpreter Core
type:  -> enhancement
versions:  -Python 3.6, Python 3.7

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34311] locale.format() and locale.format_string() cast Decimals to float

2018-08-01 Thread Eric V. Smith


Change by Eric V. Smith :


--
nosy: +eric.smith

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34311] locale.format() and locale.format_string() cast Decimals to float

2018-08-01 Thread James Emerton


New submission from James Emerton :

We use locale.format('%.2f', x, True) to convert Decimal values to strings for 
display. Unfortunately, the locale module is using %-formatting to generate the 
initial string before applying locale specific formatting. As a result, any 
value which cannot be accurately represented as a float will produce incorrect 
results.

I've built some formatting that uses new-style string formatting (and some 
internal locale functions) which corrects the problem.

Unfortunately, making this change in the locale module would require converting 
the input format string to the new syntax, so '%.2f' would become '{:.2f}'.

See also #33731

--
components: Library (Lib)
messages: 322885
nosy: jemerton
priority: normal
severity: normal
status: open
title: locale.format() and locale.format_string() cast Decimals to float
versions: Python 3.6, Python 3.7, Python 3.8

___
Python tracker 
<https://bugs.python.org/issue34311>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue29751] PyLong_FromString fails on decimals with leading zero and base=0

2017-03-08 Thread Mark Dickinson

Mark Dickinson added the comment:

Yes, PyLong_FromString is directly used by the implementation of int, and is 
also used in parsing of numeric integer literals in source:

https://github.com/python/cpython/blob/cb41b2766de646435743b6af7dd152751b54e73f/Python/ast.c#L4084

So I agree that this is a documentation bug. There's also no mention of the 
support for underscores in the documentation.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue29751] PyLong_FromString fails on decimals with leading zero and base=0

2017-03-07 Thread Serhiy Storchaka

Changes by Serhiy Storchaka :


--
assignee:  -> docs@python
components: +Documentation -Interpreter Core
nosy: +docs@python, mark.dickinson
type: behavior -> enhancement

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue29751] PyLong_FromString fails on decimals with leading zero and base=0

2017-03-07 Thread Martin Panter

Martin Panter added the comment:

My guess is this is supposed to emulate (or is actually the implementation of) 
the "int" constructor and the Python syntax. In these cases, numbers with 
leading zeros are disallowed. This was to help with Python 2 porting, where a 
leading zero specified an octal number.

>>> 010
010
  ^
SyntaxError: invalid token
>>> int("010", 0)
ValueError: invalid literal for int() with base 0: '010'

Maybe it is better to fix the documentation.

--
nosy: +martin.panter

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue29751] PyLong_FromString fails on decimals with leading zero and base=0

2017-03-07 Thread Cubi

New submission from Cubi:

Calling PyLong_FromString(str, NULL, 0) fails, if str is a string containing a 
decimal number with leading zeros, even though such strings should be parsed as 
decimal numbers according to the documentation:

"If base is 0, the radix will be determined based on the leading characters of 
str: if str starts with '0x' or '0X', radix 16 will be used; if str starts with 
'0o' or '0O', radix 8 will be used; if str starts with '0b' or '0B', radix 2 
will be used; otherwise radix 10 will be used"

Examples:
PyLong_FromString("15", NULL, 0); // Returns int(15) (Correct)
PyLong_FromString("0xF", NULL, 0); // Returns int(15) (Correct)
PyLong_FromString("015", NULL, 0); // Should return int(15), but raises 
ValueError: invalid literal for int() with base 0: '015'

Version information:
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit 
(AMD64)] on win32

--
components: Interpreter Core
messages: 289188
nosy: cubinator
priority: normal
severity: normal
status: open
title: PyLong_FromString fails on decimals with leading zero and base=0
type: behavior
versions: Python 3.5

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue29751>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue27265] Hash of different, specific Decimals created from str is the same

2016-06-09 Thread Serhiy Storchaka

Changes by Serhiy Storchaka :


--
stage:  -> resolved

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue27265] Hash of different, specific Decimals created from str is the same

2016-06-09 Thread Radosław Szalski

Radosław Szalski added the comment:

Thanks for the comments, you are both correct. I think that the issue is 
resolved now, so I'm closing this a won't fix.

--
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue27265] Hash of different, specific Decimals created from str is the same

2016-06-09 Thread Serhiy Storchaka

Serhiy Storchaka added the comment:

Note that Decimal(0.05) != Decimal('0.05').

>>> Decimal(0.05)
Decimal('0.05000277555756156289135105907917022705078125')
>>> hash(Decimal(0.05))
966367654
>>> hash(Decimal('0.05000277555756156289135105907917022705078125'))
966367654
>>> hash(0.05)
966367654

--
nosy: +serhiy.storchaka

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue27265] Hash of different, specific Decimals created from str is the same

2016-06-09 Thread Mark Dickinson

Mark Dickinson added the comment:

> the behavior differs simply based on whether the Decimal was created from a 
> string vs a float

That's not quite right: a Decimal object keeps no knowledge of how it was 
created. The behaviour differs depending on whether the value of the Decimal 
happens to be exactly representable as a Python float or not. That's necessary 
to ensure the invariant `x == y` implies `hash(x) == hash(y)` continues to hold 
across types (though Python 3 has a better way of doing this).

So for example `Decimal('0.375')` was created from a string, but will hash 
equal to the exactly equal float `0.375`:

noether:float-proofs mdickinson$ python2
Python 2.7.11 (default, May  1 2016, 08:20:00) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from decimal import Decimal
>>> hash(Decimal('0.375')), hash(Decimal(0.375))
(1610579968, 1610579968)
>>> hash(0.375)
1610579968

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue27265] Hash of different, specific Decimals created from str is the same

2016-06-09 Thread Radosław Szalski

Radosław Szalski added the comment:

Thanks for the reply and analysis, Mark.

My motivation was that as a "clueless user", I shouldn't worry about how 
Decimals are created. Given two equal numbers, I would expect their behavior 
(e.g., result of a hash) to be the same as well. In this example, the behavior 
differs simply based on whether the Decimal was created from a string vs a 
float.

However, since there are bound to be collisions, and the performance overhead 
is negligible (in case of a collision), and Python 3 solves this problem I 
agree this can be closed as "won't-fix".

--
status: pending -> open

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue27265>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue27265] Hash of different, specific Decimals created from str is the same

2016-06-08 Thread Mark Dickinson

Changes by Mark Dickinson :


--
status: open -> pending

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue27265] Hash of different, specific Decimals created from str is the same

2016-06-08 Thread Mark Dickinson

Mark Dickinson added the comment:

For what it's worth, here are timings on my machine showing the overhead of the 
extra equality check when a hash collision occurs.

Python 2.7.11 (default, Mar  1 2016, 18:08:21) 
Type "copyright", "credits" or "license" for more information.

IPython 4.2.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help  -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: from decimal import Decimal

In [2]: set1 = set([Decimal(str(n/1000.0)) for n in range(1, 10)] + 
[Decimal(str(n/100.0)) for n in range(1, 10)])

In [3]: set2 = set([Decimal(str(n/1000.0)) for n in range(2, 20)])

In [4]: print len(set1), len(set2)  # Both sets have the same length
18 18

In [5]: print len(set(map(hash, set1))), len(set(map(hash, set2)))  # But set1 
has hash collisions
9 18

In [6]: %timeit Decimal('0.005') in set1  # checking elt in the set, first 
match is the right one
The slowest run took 5.98 times longer than the fastest. This could mean that 
an intermediate result is being cached.
10 loops, best of 3: 17.4 µs per loop

In [7]: %timeit Decimal('0.05') in set1  # checking elt in the set, collision 
resolution needed
The slowest run took 5.72 times longer than the fastest. This could mean that 
an intermediate result is being cached.
10 loops, best of 3: 19.6 µs per loop

In [8]: %timeit Decimal('0.005') in set2  # should be similar to the first set1 
result
The slowest run took 5.99 times longer than the fastest. This could mean that 
an intermediate result is being cached.
10 loops, best of 3: 17.3 µs per loop

--
status: pending -> open

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue27265] Hash of different, specific Decimals created from str is the same

2016-06-08 Thread Mark Dickinson

Changes by Mark Dickinson :


--
resolution:  -> wont fix
status: open -> pending

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue27265] Hash of different, specific Decimals created from str is the same

2016-06-08 Thread Mark Dickinson

Mark Dickinson added the comment:

There's nothing wrong with two different Decimal objects having the same hash 
(indeed, it's inevitable, given that there are fewer than 2**64 hash values 
available, and many more possible Decimal objects). It only becomes a problem 
if you have a largish naturally-occurring dataset whose values all end up 
falling into the same hash bucket, resulting in linear-time dict operations 
instead of constant time.

I don't think that's the case here: each example of this form only has two 
different values with the same hash.

@Radosław Szalski: is this causing problems in a real application? If not, I 
think it should be closed as "won't fix".

Note that Python 3 is not subject to this issue: it uses a different hashing 
technique (as described in the issue 8188 that you already linked to).

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue27265] Hash of different, specific Decimals created from str is the same

2016-06-08 Thread Radosław Szalski

New submission from Radosław Szalski:

Python 2.7.11 (default, May  9 2016, 19:53:39)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from decimal import Decimal
>>> hash(Decimal('0.05')) == hash(Decimal('0.005'))
True
>>> hash(Decimal(0.05)) == hash(Decimal(0.005))
False

Interactive example: https://repl.it/CZUJ/6

Those values are numerically different and IMO should not have equal hashes. I 
am aware of the quirk with hash(-1) == hash(-2) which is at play here.
This only applies to Decimals created from strings as they are hashed 
differently than float-based ones.


What happens? The following equation is True:
>>> hash(Decimal('0.005')) == hash(Decimal('0.05'))

What I expected to happen? The following equation to be False:
>>> hash(Decimal('0.005')) == hash(Decimal('0.05'))


Platform: MacBook Pro Retina, 13", early 2015, OSX 10.11.5
Tested on Python Versions: 2.7.3, 2.7.10, 2.7.11 (installed via pyenv), all 
exhibit the same behavior


Relevant (not duplicate) issues I've found: 

http://bugs.python.org/issue10356 - decimal.py: hash of -1
http://bugs.python.org/issue8188 - Unified hash for numeric types.



---


Transcript of the interactive example: https://repl.it/CZUJ/6:

from decimal import Decimal

# These two different decimals have equal hashes
print(hash(Decimal('0.005')) == hash(Decimal('0.05')))

# Internally, Decimal's hash is computed like this (sign, exp + len(int), int)
print(hash((0, -2+len('5'), '5')) == hash((0, -3+len('5'), '5')))

# Removing constants, this becomes
print(hash(-2+len('5')) == hash(-3+len('5')))

# Which can be further simplified to:
print(hash(-1) == hash(-2))

# They both return -2, because at the CPython level, -1 is reserved for errors

# Whereas:
print(hash(Decimal(0.005)) == hash(Decimal(0.05)))

# And this is because Decimals created from floats are hashed as floats

--
components: Library (Lib)
messages: 267802
nosy: Radosław Szalski, mark.dickinson
priority: normal
severity: normal
status: open
title: Hash of different, specific Decimals created from str is the same
type: behavior
versions: Python 2.7

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue27265>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2015-03-07 Thread Tuomas Suutari

Tuomas Suutari added the comment:

Here's a patch that fixes the description for 'g' to explain what happens for 
`Decimal` and also documents the Decimal.__format__ in the documentation of the 
decimal module.

--
keywords: +patch
nosy: +Tuomas Suutari
Added file: http://bugs.python.org/file38370/issue23460.patch

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue23460
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2015-03-02 Thread Ezio Melotti

Changes by Ezio Melotti ezio.melo...@gmail.com:


--
keywords: +easy
stage:  - needs patch
type:  - enhancement
versions: +Python 2.7, Python 3.5

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue23460
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2015-03-02 Thread Mark Dickinson

Mark Dickinson added the comment:

I don't think we should close: the documentation as written explicitly says 
that the rules apply to both Decimal and float: The available presentation 
types for floating point and decimal values are   But the details listed 
for 'g' are incorrect.  We could either fix the description for 'g' to explain 
what happens for `Decimal`, or state up front that the table only applies 
directly to the `float` type, and that `Decimal` is similar but not identical.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue23460
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2015-03-01 Thread Ezio Melotti

Ezio Melotti added the comment:

Should we add a note to the format docs, or just close this?

--
nosy: +ezio.melotti, mark.dickinson

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue23460
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2015-02-14 Thread Stefan Krah

Stefan Krah added the comment:

For Decimal the cutoff point is -6 instead of -4 (following the
decimal specification instead of the C standard).

--
assignee:  - docs@python
components: +Documentation -Library (Lib)
nosy: +docs@python, skrah
type: behavior - 

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue23460
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23460] Decimals do not obey ':g' exponential notation formatting rules

2015-02-13 Thread Ian Kelly

New submission from Ian Kelly:

 '{:g}'.format(D('0.01'))
'0.01'

Formatted with '{:e}', the exponent would be -6, so per the formatting rules 
described under the 'g' specifier at 
https://docs.python.org/3/library/string.html#format-specification-mini-language
 the above should be formatted using exponential notation.

--
components: Library (Lib)
messages: 235904
nosy: ikelly
priority: normal
severity: normal
status: open
title: Decimals do not obey ':g' exponential notation formatting rules
type: behavior
versions: Python 3.4

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue23460
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Decimals and other numbers

2015-01-10 Thread alister
On Fri, 09 Jan 2015 19:57:20 -0800, Devin Jeanpierre wrote:

 On Fri, Jan 9, 2015 at 7:05 PM, Gregory Ewing
 greg.ew...@canterbury.ac.nz wrote:
 It's far from clear what *anything* multiplied by itself zero times
 should be.

 A better way of thinking about what x**n for integer n means is this:
 Start with 1, and multiply it by x n times. The result of this is
 clearly 1 when n is 0, regardless of the value of x.

 5**4 = 5*5*5*5 = 625

 No:

 5**4 = 1*5*5*5*5 5**3 = 1*5*5*5 5**2 = 1*5*5 5**1 = 1*5 5**0 = 1
 
 I never liked that, it seemed too arbitrary. How about this explanation:
 
 Assume that we know how to multiply a nonempty list numbers. so
 product([a]) == a, product([a, b]) = a * b, and so on.
 
 def product(nums):
 if len(nums) == 0:
 return ???
 return reduce(operator.mul, nums)
 
 It should be the case that given a list of factors A and B,
 product(A + B) == product(A) * product(B)   (associativity).
 We should let this rule apply even if A or B is the empty list,
 otherwise our rules are kind of stupid.
 
 Therefore, product([] + X) == product([]) * product(X)
 But since [] + X == X, product([] + X) == product(X)
 
 There's only one number like that: product([]) == 1
 
 (Of course if you choose not to have the full associativity rule for
 empty products, then anything is possible.)
 
 -- Devin

The general theory behind logarithms explains why it is excepted that any 
number raised to the power of 0 =1

take  X^3 * x^ 4 = X^7 achieved simply by adding the indices
if you wanted to do X *1 using the same method what would you need to add 
to the index of X (X^1 ) to get X (X^1) - Answer 0 therefore X^0 = 1

This theoretically works regardless of the  value of x you choose for the 
base , of course in practice it is not possible to work in a number base 
of 0 which is where things get into the indeterminate as it contradicts 
the other provable fact that ) * anything is 0.

These edge case contradictions can easily cause my brain into an in 
finite recursive loop.

it is as confusing as the concept that there are different values of 
infinity (some larger than others!)





-- 
Ya'll hear about the geometer who went to the beach to catch some
rays and became a tangent ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Gregory Ewing

Steven D'Aprano wrote:

I'm just sketching an informal proof. If you want to make it vigorous

   

I think the usual term is rigorous, unless the mathematician
is taking some kind of stimulant... :-)

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Gregory Ewing

Steven D'Aprano wrote:

Arguably, *integer* 0**0 could be zero, on the basis that you can't take
limits of integer-valued quantities, and zero times itself zero times
surely has to be zero.


It's far from clear what *anything* multiplied by
itself zero times should be.

A better way of thinking about what x**n for integer
n means is this: Start with 1, and multiply it by
x n times. The result of this is clearly 1 when n
is 0, regardless of the value of x.

 5**4 = 5*5*5*5 = 625

No:

5**4 = 1*5*5*5*5
5**3 = 1*5*5*5
5**2 = 1*5*5
5**1 = 1*5
5**0 = 1

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Devin Jeanpierre
On Fri, Jan 9, 2015 at 2:20 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
-snip-
 I don't understand what you're trying to say here. You can't just
 arbitrarily declare that 0**1 equals something other than 0 (or for that
 matter, doesn't equal anything at all).

You can, actually. It's just silly. (Similarly, you can declare that
0**0 is something other than 1 (or for that matter, doesn't equal
anything at all), but it's silly.)

 Can we agree that 0**1 is well-defined and get back to 0**0?

Believe it or not I actually misread your whole thing and thought we
were talking about 0**0. Otherwise I would've been much briefer...

 Not quite. I agree that, *generally speaking* having 0**0 equal 1 is the
 right answer, or at least *a* right answer, but not always. It depends on
 how you get to 0**0...

 You don't get to a number. Those are limits. Limits and arithmetic
 are different.

 (Well, sort of. :)

 Yes, sort of :-)

I was alluding to the definition of the reals.

 Of course you can get to numbers. We start with counting, that's a way
 to get to the natural numbers, by applying the successor function
 repeatedly until we reach the one we want. Or you can get to pi by
 generating an infinite sequence of closer and closer approximations. Or an
 infinite series. Or an infinite product. Or an infinite continued fraction.
 All of these ways to get to pi converge on the same result.

Yes, all numbers can be represented as a converging limit. However,
that does not mean that the way you compute the result of a function
like x**y is by taking the limit as its arguments approach the input:
that procedure works only for continuous functions. x**y is not
continuous at 0, so this style of computation cannot give you an
answer.

 If 0**0 has a value, we can give that number a name. Let's call it Q. There
 are different ways to evaluate Q:

 lim x - 0 of sin(x)/x  gives 1

 lim x - 0 of x**0  gives 1

 lim x - 0 of 0**x  gives 0

This is a proof that f(x, y) = x**y is not continuous around 0, 0. It
is not a proof that it is undefined at 0, 0, in fact, it says nothing
about the value.

 0**0 = 0**(5-5) = 0**5 / 0**5 = 0/0  gives indeterminate

Here is a nearly identical proof that 0**1 is indeterminate: 0 =
0**1 = 0**(5 - 4) = 0**5 / 0**4 = 0/0 gives indeterminate.

The fact that you can construct a nonsensical expression from an
expression doesn't mean the original expression was nonsensical. In
this case, your proof was invalid, because 0**(X-Y) is not equivalent
to 0**X/0**Y.

 So we have a problem. Since all these ways to get to Q fail to converge,
 the obvious answer is to declare that Q doesn't exist and that 0**0 is
 indeterminate, and that is what many mathematicians do:

That isn't what indeterminate means.

 However, this begs the question of what we mean by 0**0.

 In the case of m**n, with both m and n positive integers, there is an
 intuitively obvious definition for exponentiation: repeated multiplication.
 But there's no obvious meaning for exponentiation when both m and n are
 zero, hence we (meaning, mathematicians) have to define what it means. So
 long as that definition doesn't lead to contradiction, we can make any
 choice we like.

Sorry, I don't follow. n**0 as repeated multiplication makes perfect
sense: we don't perform any multiplications, but if we did, we'd be
multiplying 'n's. 0**m as repeated multiplication makes perfect sense:
whatever we multiply, it's a bunch of 0s. Why doesn't 0**0 make sense?
We don't perform any multiplications, but if we did, we'd be
multiplying 0s.

If we don't perform any multiplications, the things we didn't multiply
don't matter. Whether they are fives, sevens, or zeroes, the answer is
the same: 1.

 Since you can get difference results depending on the method you use to
 calculate it, the technically correct result is that 0**0 is
 indeterminate.

 No, only limits are indeterminate. Calculations not involving limits
 cannot be indeterminate.

 Do tell me what 0/0 equals, if it is not indeterminate.

0/0 is undefined, it isn't indeterminate.

Indeterminate forms are a way of expressing limits where you have
performed a lossy substitution. That is: the limit as x approaches a
of 0/0 is an indeterminate form.

 In the real number system, infinity does not exist. It only exists in
 limits or extended number systems.

 Yes, you are technically correct, the best kind of correct.

 I'm just sketching an informal proof. If you want to make it vigorous by
 using limits, be my guest. It doesn't change the conclusion.

No, the point is that limits are irrelevant.

As has been proven countlessly many times, x**y is not continuous
around the origin. This has no bearing on whether it takes a value at
the origin.


 [...]
 Arguably, *integer* 0**0 could be zero, on the basis that you can't take
 limits of integer-valued quantities, and zero times itself zero times
 surely has to be zero.

 No. No no no. On natural numbers no other thing makes sense than 1.

Re: Decimals and other numbers

2015-01-09 Thread Devin Jeanpierre
On Fri, Jan 9, 2015 at 7:05 PM, Gregory Ewing
greg.ew...@canterbury.ac.nz wrote:
 It's far from clear what *anything* multiplied by
 itself zero times should be.

 A better way of thinking about what x**n for integer
 n means is this: Start with 1, and multiply it by
 x n times. The result of this is clearly 1 when n
 is 0, regardless of the value of x.

 5**4 = 5*5*5*5 = 625

 No:

 5**4 = 1*5*5*5*5
 5**3 = 1*5*5*5
 5**2 = 1*5*5
 5**1 = 1*5
 5**0 = 1

I never liked that, it seemed too arbitrary. How about this explanation:

Assume that we know how to multiply a nonempty list numbers. so
product([a]) == a, product([a, b]) = a * b, and so on.

def product(nums):
if len(nums) == 0:
return ???
return reduce(operator.mul, nums)

It should be the case that given a list of factors A and B,
product(A + B) == product(A) * product(B)   (associativity).
We should let this rule apply even if A or B is the empty list,
otherwise our rules are kind of stupid.

Therefore, product([] + X) == product([]) * product(X)
But since [] + X == X, product([] + X) == product(X)

There's only one number like that: product([]) == 1

(Of course if you choose not to have the full associativity rule for
empty products, then anything is possible.)

-- Devin
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Steven D'Aprano
Devin Jeanpierre wrote:

 On Thu, Jan 8, 2015 at 6:43 PM, Dave Angel da...@davea.name wrote:
 What you don't say is which behavior you actually expected.  Since 0**0
 is undefined mathematically, I'd expect either an exception or a NAN
 result.
 
 It can be undefined, if you choose for it to be. You can also choose
 to not define 0**1, of course. 

No you can't -- that would make arithmetic inconsistent. 0**1 is perfectly
well defined as 0 however you look at it:

lim of x - 0 of x**1 = 0
lim of y - 1 of 0**y = 0


 If 0**0 is defined, it must be 1. I 
 Googled around to find a mathematician to back me up, here:
 http://arxiv.org/abs/math/9205211 (page 6, ripples).

Not quite. I agree that, *generally speaking* having 0**0 equal 1 is the
right answer, or at least *a* right answer, but not always. It depends on
how you get to 0**0...

Since you can get difference results depending on the method you use to
calculate it, the technically correct result is that 0**0 is
indeterminate. But that's not terribly useful, and mathematicians with a
pragmatic bent (i.e. most of them) define 0**0 == 1 on the basis that it is
justifiable and useful, while 0**0 = 0 is justifiable but not useful and
leaving it as indeterminate is just a pain.

One argument comes from taking limits of x**y. If you set x to zero, and
take the limit as y approaches 1, you get:

lim of y - 0 of 0**y = 0

But if you set y to 0, and take the limit as x approaches 0, you get:

lim of x - 0 of x**0 = 1

There is a discontinuity in the graph of x**y, and no matter what value you
define 0**0 as, you cannot get rid of that discontinuity. Hence
indeterminate.

Here's another argument for keeping it indeterminate. Suppose we let 0**0 =
some value Q. Let's take the logarithm of Q.

log(Q) = log (0**0)

But log (a**b) = b*log(a), so:

log(Q) = 0*log(0)

What's log(0)? If we take the limit from above, we get log(x) - -infinity.
If we take the limit from below, we get a complex infinity, so let's ignore
the limit from below and informally write:

log(Q) = 0*-inf

What is zero times infinity? In the real number system, that is
indeterminate, again because it depends on how you calculate it: naively it
sounds like it should be 0, but infinity is pretty big and if you add up
enough zeroes in the right way you can actually get something non-zero.
There's no one right answer. So if the log of Q is indeterminate, then so
must be Q.

But there are a host of good reasons for preferring 0**0 = 1. Donald Knuth
writes (using ^ for power):

Some textbooks leave the quantity 0^0 undefined, because the 
functions 0^x and x^0 have different limiting values when x 
decreases to 0. But this is a mistake. We must define x^0=1 
for all x , if the binomial theorem is to be valid when x=0, 
y=0, and/or x=-y. The theorem is too important to be arbitrarily
restricted! By contrast, the function 0^x is quite unimportant.

More discussion here:

http://mathforum.org/dr.math/faq/faq.0.to.0.power.html


 I expected 1, nan, or an exception, but more importantly, I expected
 it to be the same for floats and decimals.

Arguably, *integer* 0**0 could be zero, on the basis that you can't take
limits of integer-valued quantities, and zero times itself zero times
surely has to be zero.

But in practice, I agree that 0**0 should give the same result regardless of
the type of zeroes used, and if the result is a number rather than a NAN or
an exception, it should be 1.




-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Devin Jeanpierre
Marko, your argument is this function x**y(a, x) must be continuous
on [0, inf), and to be continuous at 0, 0**0 must be a. Since there
are many possible values of a, this is not a justification, this is
a proof by contradiction that the premise was faulty: x**y(a, x)
doesn't have to be continuous after all.

0**0 is 1, which makes some functions continuous and some functions
not, and who cares? It's 1 because that's what is demanded by
combinatorial definitions of exponentiation, and its origins in the
domain of the natural numbers.  Knuth says that thought of
combinatorially on the naturals, x**y counts the number of mappings
from a set of x values to a set of y values. Clearly there's only one
mapping from the empty set to itself: the empty mapping. Number theory
demands that performing multiplication among an empty bag of numbers
gives you the result of 1 -- even if the empty bag is an empty bag of
zeroes instead of an empty bag of fives. The result does not change.

Either of those ideas about exponentiation can be thought of as
descriptions of its behavior, or as definitions. They completely
describe its behavior on the naturals, from which we derive its
behavior on the reals.

-- Devin

On Thu, Jan 8, 2015 at 11:28 PM, Marko Rauhamaa ma...@pacujo.net wrote:
 Devin Jeanpierre jeanpierr...@gmail.com:

 If 0**0 is defined, it must be 1.

 You can justify any value a within [0, 1]. For example, choose

y(a, x) = log(a, x)

 Then,

 limy(a, x) = 0
x - 0+

 and:

lim[x - 0+] x**y(a, x) = a

 For example,

 a = 0.5
 x = 1e-100
 y = math.log(a, x)
 y
0.0030102999566398118
 x**y
0.5


 Marko
 --
 https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Jussi Piitulainen
Devin Jeanpierre writes:

[...]

 domain of the natural numbers.  Knuth says that thought of
 combinatorially on the naturals, x**y counts the number of mappings
 from a set of x values to a set of y values.

It's the other way around, of course: from a set of y values to a set
of x values.

Which reminds me of a question that once made me smile, even laugh,
and still does: 2**3 is almost 3**2 but not quite - what gives?

 Clearly there's only one mapping from the empty set to itself: the

[...]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Marko Rauhamaa
Chris Angelico ros...@gmail.com:

 I'm not a mathematical expert, so I don't quite 'get' this. How does
 this justify 0**0 being equal to 0.5?

Many operations like this are defined in terms of some very strong
argument of uniqueness. Ultimately, the key point is safety in
mathematical deductions. One minimal requirement would be:

 limf(x, y)
   (x, y) - (0, 0)

must be defined (See URL: http://en.wikipedia.org/wiki/Limit_of_a_func
tion#Functions_of_more_than_one_variable).

If you get sloppy, there is a real risk of terrible logical mistakes and
wrong results. I think having 0**0 return a value is as irresponsible as
having 0/0 return a value.

(The very same principle is used to define 0+0 and 0*0 as well.)


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Marko Rauhamaa
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info:

 Devin Jeanpierre wrote:
 No you can't -- that would make arithmetic inconsistent. 0**1 is
 perfectly well defined as 0 however you look at it:

You *could* leave 0**1 undefined. You *could* leave 7+0 undefined.
However, that would make mathematical proofs more complex as they would
be riddled with if/else branches.

That's the whole point of silly no-op definitions such as a+0 or b**1;
they make mathematical proofs much more concise and feasible. It is
precious to be able to have such ideal cases defined, and you'd like
to do it everywhere. Unfortunately, it is not possible everywhere so you
just have to supply the necessary if/else branches in your proof.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Steven D'Aprano
I think we're in violent agreement here, nevertheless I think you're right
for the wrong reasons. See below...


Devin Jeanpierre wrote:

 On Fri, Jan 9, 2015 at 12:49 AM, Steven D'Aprano
 steve+comp.lang.pyt...@pearwood.info wrote:
 Devin Jeanpierre wrote:

 On Thu, Jan 8, 2015 at 6:43 PM, Dave Angel da...@davea.name wrote:
 What you don't say is which behavior you actually expected.  Since 0**0
 is undefined mathematically, I'd expect either an exception or a NAN
 result.

 It can be undefined, if you choose for it to be. You can also choose
 to not define 0**1, of course.

 No you can't -- that would make arithmetic inconsistent. 0**1 is
 perfectly well defined as 0 however you look at it:

 lim of x - 0 of x**1 = 0
 lim of y - 1 of 0**y = 0

I should have used x for the variable in both expressions:

lim of x - 0 of x**1 = 0
lim of x - 1 of 0**x = 0

 
 This is a misunderstanding of limits. Limits are allowed to differ
 from the actual evaluated result when you substitute the limit point:
 that's what it means to be discontinuous.

That's true, if the function is discontinuous. But it's irrelevant here.
Neither x**1 nor 0**x are discontinuous, they're both continuous, and both
have the same limit for x-0 in the first place and x-1 in the second.
However you do it, 0**1 must be 0.


 What you call making  arithmetic inconsistent, I call making the
 function inside the limit discontinuous at 0.

I don't understand what you're trying to say here. You can't just
arbitrarily declare that 0**1 equals something other than 0 (or for that
matter, doesn't equal anything at all). 

0**1 = (5-5)**1 = 5-5 = 0

If you want to say that 0**1 != 0, then you likewise have to say that 
5-5 != 0, otherwise arithmetic is inconsistent.

Can we agree that 0**1 is well-defined and get back to 0**0?


 If 0**0 is defined, it must be 1. I
 Googled around to find a mathematician to back me up, here:
 http://arxiv.org/abs/math/9205211 (page 6, ripples).

 Not quite. I agree that, *generally speaking* having 0**0 equal 1 is the
 right answer, or at least *a* right answer, but not always. It depends on
 how you get to 0**0...
 
 You don't get to a number. Those are limits. Limits and arithmetic
 are different.
 
 (Well, sort of. :)

Yes, sort of :-)

Of course you can get to numbers. We start with counting, that's a way
to get to the natural numbers, by applying the successor function
repeatedly until we reach the one we want. Or you can get to pi by
generating an infinite sequence of closer and closer approximations. Or an
infinite series. Or an infinite product. Or an infinite continued fraction.
All of these ways to get to pi converge on the same result.

If 0**0 has a value, we can give that number a name. Let's call it Q. There
are different ways to evaluate Q:

lim x - 0 of sin(x)/x  gives 1

lim x - 0 of x**0  gives 1

lim x - 0 of 0**x  gives 0

0**0 = 0**(5-5) = 0**5 / 0**5 = 0/0  gives indeterminate


So we have a problem. Since all these ways to get to Q fail to converge,
the obvious answer is to declare that Q doesn't exist and that 0**0 is
indeterminate, and that is what many mathematicians do:

http://mathworld.wolfram.com/Indeterminate.html

However, this begs the question of what we mean by 0**0.

In the case of m**n, with both m and n positive integers, there is an
intuitively obvious definition for exponentiation: repeated multiplication.
But there's no obvious meaning for exponentiation when both m and n are
zero, hence we (meaning, mathematicians) have to define what it means. So
long as that definition doesn't lead to contradiction, we can make any
choice we like.

Hence some mathematicians decide that things like the Binomial Theorem are
far more important than 0**x, and so they define 0**0 as 1. They can
justify that definition, of course, it's not just arbitrary, but the
important thing is that mathematicians working in other fields can and do
sometimes use a slightly different definition, one where 0**0 is
indeterminate.

http://www.askamathematician.com/2010/12/q-what-does-00-zero-raised-to-the-zeroth-power-equal-why-do-mathematicians-and-high-school-teachers-disagree/


 Since you can get difference results depending on the method you use to
 calculate it, the technically correct result is that 0**0 is
 indeterminate.
 
 No, only limits are indeterminate. Calculations not involving limits
 cannot be indeterminate.

Do tell me what 0/0 equals, if it is not indeterminate.


 -snip-
 log(Q) = 0*-inf

 What is zero times infinity? In the real number system, that is
 indeterminate, again because it depends on how you calculate it
 
 In the real number system, infinity does not exist. It only exists in
 limits or extended number systems.

Yes, you are technically correct, the best kind of correct.

I'm just sketching an informal proof. If you want to make it vigorous by
using limits, be my guest. It doesn't change the conclusion.


[...]
 Arguably, *integer* 0**0 could be zero, on the basis that you can't take

Re: Decimals and other numbers

2015-01-09 Thread Devin Jeanpierre
On Fri, Jan 9, 2015 at 12:58 AM, Devin Jeanpierre
jeanpierr...@gmail.com wrote:
 Arguably, *integer* 0**0 could be zero, on the basis that you can't take
 limits of integer-valued quantities, and zero times itself zero times
 surely has to be zero.

I should have responded in more detail here, sorry.

If you aren't performing any multiplication, why does it matter what
numbers you are multiplying? Doing no multiplications of five is the
same as doing no multiplications of two is the same as doing no
multiplications of... 0.

You can define it to be 0 but only if you are multiplying an empty bag
of zeroes, but it's hard to imagine what makes an empty bag of zeroes
different from an empty bag of fives. It really surely is *not* the
case.

Obviously, this kind of ridiculousness comes naturally to Java and C++
programmers, with their statically typed collections. It's no surprise
that's where the Decimal spec came from. ;)

-- Devin
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Marko Rauhamaa
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info:

 mathematicians with a pragmatic bent

You shouldn't call engineers and scientists mathematicians (with a
pragmatic bent). Rigor is an absolute requirement for any mathematics.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Devin Jeanpierre
On Fri, Jan 9, 2015 at 12:49 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 Devin Jeanpierre wrote:

 On Thu, Jan 8, 2015 at 6:43 PM, Dave Angel da...@davea.name wrote:
 What you don't say is which behavior you actually expected.  Since 0**0
 is undefined mathematically, I'd expect either an exception or a NAN
 result.

 It can be undefined, if you choose for it to be. You can also choose
 to not define 0**1, of course.

 No you can't -- that would make arithmetic inconsistent. 0**1 is perfectly
 well defined as 0 however you look at it:

 lim of x - 0 of x**1 = 0
 lim of y - 1 of 0**y = 0

This is a misunderstanding of limits. Limits are allowed to differ
from the actual evaluated result when you substitute the limit point:
that's what it means to be discontinuous.

What you call making  arithmetic inconsistent, I call making the
function inside the limit discontinuous at 0.


 If 0**0 is defined, it must be 1. I
 Googled around to find a mathematician to back me up, here:
 http://arxiv.org/abs/math/9205211 (page 6, ripples).

 Not quite. I agree that, *generally speaking* having 0**0 equal 1 is the
 right answer, or at least *a* right answer, but not always. It depends on
 how you get to 0**0...

You don't get to a number. Those are limits. Limits and arithmetic
are different.

(Well, sort of. :)

 Since you can get difference results depending on the method you use to
 calculate it, the technically correct result is that 0**0 is
 indeterminate.

No, only limits are indeterminate. Calculations not involving limits
cannot be indeterminate.

-snip-
 log(Q) = 0*-inf

 What is zero times infinity? In the real number system, that is
 indeterminate, again because it depends on how you calculate it

In the real number system, infinity does not exist. It only exists in
limits or extended number systems.

 : naively it
 sounds like it should be 0, but infinity is pretty big and if you add up
 enough zeroes in the right way you can actually get something non-zero.
 There's no one right answer. So if the log of Q is indeterminate, then so
 must be Q.

 But there are a host of good reasons for preferring 0**0 = 1. Donald Knuth
 writes (using ^ for power):

 Some textbooks leave the quantity 0^0 undefined, because the
 functions 0^x and x^0 have different limiting values when x
 decreases to 0. But this is a mistake. We must define x^0=1
 for all x , if the binomial theorem is to be valid when x=0,
 y=0, and/or x=-y. The theorem is too important to be arbitrarily
 restricted! By contrast, the function 0^x is quite unimportant.

 More discussion here:

 http://mathforum.org/dr.math/faq/faq.0.to.0.power.html

I've already been citing Knuth. :P

 I expected 1, nan, or an exception, but more importantly, I expected
 it to be the same for floats and decimals.

 Arguably, *integer* 0**0 could be zero, on the basis that you can't take
 limits of integer-valued quantities, and zero times itself zero times
 surely has to be zero.

No. No no no. On natural numbers no other thing makes sense than 1.
All of the definitions of exponentiation for natural numbers require
it, except for those derived from analytical notions of
exponentiation. (Integers just give you ratios of natural
exponentials, so again no.)

-- Devin
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Chris Angelico
On Fri, Jan 9, 2015 at 9:20 PM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 On the basis that m**n means m multiplied by itself n times:

 5**4 = 5*5*5*5 = 625

 that gives us:

 0**0 = zero multiplied by itself zero times.

 You can multiply 0 by any number you like, and the answer will always be 0,
 not 1. Even if that other number is 0, the answer is still 0.

5 * 0 * 0 * 0 * 0 = 0

You can multiply 5 by 0 any number of times you like, and the answer
will always be 0... unless you never multiply it by 0 at all, in which
case it'll be 5. Multiplying 0 by any number, including 0, is 0... but
*not* multiplying 0 by 0 doesn't have to give 0. 0**0 is the result of
not multiplying any zeroes together, so it doesn't follow the rules of
multiplying zeroes together.

Look at it another way. 6**x modulo 10 will always be 6, right? 6, 36,
216... the rules for multiplying mean that the last digit will be
consistent. (That's how we can know what the last digits of Graham's
Number are, despite having no way to even comprehend its scale.) So
what's 6**0? Is that going to end with 6, too, to be consistent? No,
because we're not multiplying any sixes in, so the answer's simply 1.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Steven D'Aprano
Marko Rauhamaa wrote:

 Steven D'Aprano steve+comp.lang.pyt...@pearwood.info:
 
 mathematicians with a pragmatic bent
 
 You shouldn't call engineers and scientists mathematicians (with a
 pragmatic bent). Rigor is an absolute requirement for any mathematics.

I wasn't referring to engineers, scientists, short-order cooks or cat walk
models. I was referring to mathematicians.

Mathematicians with a pragmatic bent. Or to put it another way, the
intersection between the set of pragmatic people and the set of
mathematicians.




-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Steven D'Aprano
I want to emphasis that I'm not really arguing that 0**0 should evaluate as
0. That's probably the least useful thing we can have out of the four
possibilities:

- return 1
- return NAN
- raise an exception
- return 0

But in the spirit of the Devil's Advocate, I mentioned that there was an
argument to be made for having integer 0**0 return 0. Intuitively, we have:

0**5 = 0
0**4 = 0
0**3 = 0
0**2 = 0
0**1 = 0
0**0 = ?

It's not hard to see that 0**n = 0 for every n except 0, so why make an
exception for 0? I stress that there are *better* arguments for making that
exception and having 0**0 defined as 1. My argument is merely that there is
*an argument* for having 0**0 return 0.

I could put it this way:

If you start with nothing and raise it to the power of nothing, then there
is nothing to exponentiate and you're left with nothing.

More below.

Chris Angelico wrote:

 On Fri, Jan 9, 2015 at 9:20 PM, Steven D'Aprano
 steve+comp.lang.pyt...@pearwood.info wrote:
 On the basis that m**n means m multiplied by itself n times:

 5**4 = 5*5*5*5 = 625

 that gives us:

 0**0 = zero multiplied by itself zero times.

 You can multiply 0 by any number you like, and the answer will always be
 0, not 1. Even if that other number is 0, the answer is still 0.
 
 5 * 0 * 0 * 0 * 0 = 0

Where did the 5 come from?

You're effectively saying that 0**0 becomes 5*0**0, then cancelling the 0**0
because they're all zeroes and so don't matter, leaving 5. And that simply
doesn't work. If it did work, there's nothing special about 5, we could use
18 instead:

0**0 = 5*0**0 = 5

but 0**0 = 18*0**0 = 18
therefore 5 = 18.

Yay maths! :-)


 You can multiply 5 by 0 any number of times you like, and the answer 
 will always be 0... unless you never multiply it by 0 at all, in which
 case it'll be 5. Multiplying 0 by any number, including 0, is 0... but 
 *not* multiplying 0 by 0 doesn't have to give 0. 0**0 is the result of
 not multiplying any zeroes together, so it doesn't follow the rules of
 multiplying zeroes together.

If you want to be vigorous, we're both talking nonsense. Exponentiation in
terms of repeated multiplication only works for non-zero powers. Talking
about multiplication by itself zero times raises the question what the
hell do you mean by multiplication by itself zero times?

There are ways to make this vigorous. The problem is, with 0**0, you get a
different answer depending on how you make it vigorous. Hence 0**0 is
indeterminate.


 Look at it another way. 6**x modulo 10 will always be 6, right? 6, 36, 
 216... the rules for multiplying mean that the last digit will be
 consistent. (That's how we can know what the last digits of Graham's
 Number are, despite having no way to even comprehend its scale.) 

Oh, after going through some of the discussions on Python-ideas, I'm pretty
sure I comprehend its scale...


 So 
 what's 6**0? Is that going to end with 6, too, to be consistent? No,
 because we're not multiplying any sixes in, so the answer's simply 1.

Why 1? Why not 3? Or 0?

The answer is, it needs to be 1 to be consistent with the Index Laws such as
a**(b-c) = a**b / a**c. That's a good answer, and it works great for a=6:

6**0 = 6**(2-2) = 6**2 / 6**2 = 36/36 = 1

(There's nothing special about 2, I could have used 0 = 97-97, or any other
positive value.)

But it doesn't work when the base is zero:

0**0 = 0**(2-2) = 0**2 / 0**2 = 0/0 = 

Oops. There's that pesky indeterminate result again.



-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-09 Thread Chris Angelico
On Fri, Jan 9, 2015 at 11:24 PM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 5 * 0 * 0 * 0 * 0 = 0

 Where did the 5 come from?

 You're effectively saying that 0**0 becomes 5*0**0, then cancelling the 0**0
 because they're all zeroes and so don't matter, leaving 5. And that simply
 doesn't work. If it did work, there's nothing special about 5, we could use
 18 instead:

 0**0 = 5*0**0 = 5

 but 0**0 = 18*0**0 = 18
 therefore 5 = 18.

 Yay maths! :-)

To clarify, I'm following this sequence:

5 * 0**4 = 5 * 0 * 0 * 0 * 0 = 0
5 * 0**3 = 5 * 0 * 0 * 0 = 0
5 * 0**2 = 5 * 0 * 0 = 0
5 * 0**1 = 5 * 0 = 0
5 * 0**0 = 5 = ?

Multiplication by zero is idempotent; any number of multiplications
beyond the first won't change the result. But that doesn't mean that
never multiplying by zero will have the same result. I think it's
fairly obvious in this example that the pattern does NOT continue to
the case where you're multiplying in no zeroes.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-08 Thread Chris Rebert
On Thu, Jan 8, 2015 at 6:33 PM, Devin Jeanpierre jeanpierr...@gmail.com wrote:
 I noticed some very PHP-ish behavior today:

 import decimal
 x = 0
 y = float(x)
 z = decimal.Decimal(x)
 x == y == z == x
 True
 x ** x
 1
 y**y
 1.0
 z**z
 Traceback (most recent call last):
   File stdin, line 1, in module
   File /usr/lib/python2.7/decimal.py, line 2216, in __pow__
 return context._raise_error(InvalidOperation, '0 ** 0')
   File /usr/lib/python2.7/decimal.py, line 3872, in _raise_error
 raise error(explanation)
 decimal.InvalidOperation: 0 ** 0

 I'd file a bug report but I'm anticipating some rational (heh)
 explanation. Any ideas?

The `decimal` std lib module implements the General Decimal Arithmetic
Specification (http://speleotrove.com/decimal/decarith.html ).
In the Exceptional conditions section
(http://speleotrove.com/decimal/daexcep.html ), it specifies the
following:
Invalid operation
This occurs and signals invalid-operation if:
[...]
* both operands of the power operation are zero

No idea why it chose to differ from IEEE-754.

Cheers,
Chris
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-08 Thread Devin Jeanpierre
On Thu, Jan 8, 2015 at 6:43 PM, Dave Angel da...@davea.name wrote:
 What you don't say is which behavior you actually expected.  Since 0**0 is
 undefined mathematically, I'd expect either an exception or a NAN result.

It can be undefined, if you choose for it to be. You can also choose
to not define 0**1, of course. If 0**0 is defined, it must be 1. I
Googled around to find a mathematician to back me up, here:
http://arxiv.org/abs/math/9205211 (page 6, ripples).

I expected 1, nan, or an exception, but more importantly, I expected
it to be the same for floats and decimals.

BTW, Ben, you linked to a file on your hard drive. You meant
https://docs.python.org/2/library/decimal.html#decimal.InvalidOperation

-- Devin
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-08 Thread Devin Jeanpierre
Thanks Ben, with your encouragement I have filed
http://bugs.python.org/issue23201

-- Devin

On Thu, Jan 8, 2015 at 7:03 PM, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Dave Angel da...@davea.name writes:

 What you don't say is which behavior you actually expected.  Since
 0**0 is undefined mathematically, I'd expect either an exception or a
 NAN result.

 Do you think that the ‘int’ and ‘float’ types, which do produce a number
 result for ‘0 ** 0’, are buggy and should be fixed?

 I think the inconsistency is unnecessarily confusing. Perhaps the
 consistency is in standards outside Python, but I think there is cause
 here either for a change of behaviour or, if ther eis a good rationale
 for the incompatible behaviours, to document the rationale. In either
 case, a bug report is warranted IMO.

 --
  \ “We are all agreed that your theory is crazy. The question that |
   `\  divides us is whether it is crazy enough to have a chance of |
 _o__)being correct.” —Niels Bohr (to Wolfgang Pauli), 1958 |
 Ben Finney

 --
 https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Decimals and other numbers

2015-01-08 Thread Devin Jeanpierre
I noticed some very PHP-ish behavior today:

 import decimal
 x = 0
 y = float(x)
 z = decimal.Decimal(x)
 x == y == z == x
True
 x ** x
1
 y**y
1.0
 z**z
Traceback (most recent call last):
  File stdin, line 1, in module
  File /usr/lib/python2.7/decimal.py, line 2216, in __pow__
return context._raise_error(InvalidOperation, '0 ** 0')
  File /usr/lib/python2.7/decimal.py, line 3872, in _raise_error
raise error(explanation)
decimal.InvalidOperation: 0 ** 0


I'd file a bug report but I'm anticipating some rational (heh)
explanation. Any ideas?

Python 3.4 also raises this exception, but the error message is less
informative. (decimal.InvalidOperation: [class
'decimal.InvalidOperation']).

-- Devin
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-08 Thread Ben Finney
Dave Angel da...@davea.name writes:

 What you don't say is which behavior you actually expected.  Since
 0**0 is undefined mathematically, I'd expect either an exception or a
 NAN result.

Do you think that the ‘int’ and ‘float’ types, which do produce a number
result for ‘0 ** 0’, are buggy and should be fixed?

I think the inconsistency is unnecessarily confusing. Perhaps the
consistency is in standards outside Python, but I think there is cause
here either for a change of behaviour or, if ther eis a good rationale
for the incompatible behaviours, to document the rationale. In either
case, a bug report is warranted IMO.

-- 
 \ “We are all agreed that your theory is crazy. The question that |
  `\  divides us is whether it is crazy enough to have a chance of |
_o__)being correct.” —Niels Bohr (to Wolfgang Pauli), 1958 |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-08 Thread Dave Angel

On 01/08/2015 09:33 PM, Devin Jeanpierre wrote:

I noticed some very PHP-ish behavior today:


import decimal
x = 0
y = float(x)
z = decimal.Decimal(x)
x == y == z == x

True

x ** x

1

y**y

1.0

z**z

Traceback (most recent call last):
   File stdin, line 1, in module
   File /usr/lib/python2.7/decimal.py, line 2216, in __pow__
 return context._raise_error(InvalidOperation, '0 ** 0')
   File /usr/lib/python2.7/decimal.py, line 3872, in _raise_error
 raise error(explanation)
decimal.InvalidOperation: 0 ** 0


I'd file a bug report but I'm anticipating some rational (heh)
explanation. Any ideas?

Python 3.4 also raises this exception, but the error message is less
informative. (decimal.InvalidOperation: [class
'decimal.InvalidOperation']).



What you don't say is which behavior you actually expected.  Since 0**0 
is undefined mathematically, I'd expect either an exception or a NAN result.



--
DaveA
--
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-08 Thread Marko Rauhamaa
Dave Angel da...@davea.name:

 What you don't say is which behavior you actually expected. Since 0**0
 is undefined mathematically, I'd expect either an exception or a NAN
 result.

IEEE 754 mandates that 0**0 should evaluate to 1:

   URL: http://en.wikipedia.org/wiki/NaN#Operations_generating_NaN

The standard pow function and the integer exponent pown function
define 0**0, 1**∞, and ∞**0 as 1.

The powr function defines all three indeterminate forms as invalid
operations and so returns NaN.

Should IEEE 754's anomalies spill over to decimal, is a different
question.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-08 Thread Dave Angel

On 01/09/2015 02:37 AM, Chris Angelico wrote:

On Fri, Jan 9, 2015 at 6:28 PM, Marko Rauhamaa ma...@pacujo.net wrote:

Devin Jeanpierre jeanpierr...@gmail.com:


If 0**0 is defined, it must be 1.


You can justify any value a within [0, 1]. For example, choose

y(a, x) = log(a, x)

Then,

 limy(a, x) = 0
x - 0+

and:

lim[x - 0+] x**y(a, x) = a

For example,

 a = 0.5
 x = 1e-100
 y = math.log(a, x)
 y
0.0030102999566398118
 x**y
0.5


I'm not a mathematical expert, so I don't quite 'get' this. How does
this justify 0**0 being equal to 0.5?

I know how to justify 0 and 1, and NaN (on the basis that both 0 and 1
can be justified). I don't follow how other values can be used.


Roughly speaking, the idea is to have a relationship between x and y, 
such that even though they each get arbitrarily close to zero, the 
formula x**y is a constant 5.


So he plugged in 1e-100.  But if you plugged in 1e-5  and could 
handle the precision, the result x**y  would still be 0.5





--
DaveA
--
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-08 Thread Marko Rauhamaa
Devin Jeanpierre jeanpierr...@gmail.com:

 If 0**0 is defined, it must be 1.

You can justify any value a within [0, 1]. For example, choose

   y(a, x) = log(a, x)

Then,

limy(a, x) = 0
   x - 0+

and:

   lim[x - 0+] x**y(a, x) = a

For example,

a = 0.5
x = 1e-100
y = math.log(a, x)
y
   0.0030102999566398118
x**y
   0.5


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-08 Thread Chris Angelico
On Fri, Jan 9, 2015 at 6:28 PM, Marko Rauhamaa ma...@pacujo.net wrote:
 Devin Jeanpierre jeanpierr...@gmail.com:

 If 0**0 is defined, it must be 1.

 You can justify any value a within [0, 1]. For example, choose

y(a, x) = log(a, x)

 Then,

 limy(a, x) = 0
x - 0+

 and:

lim[x - 0+] x**y(a, x) = a

 For example,

 a = 0.5
 x = 1e-100
 y = math.log(a, x)
 y
0.0030102999566398118
 x**y
0.5

I'm not a mathematical expert, so I don't quite 'get' this. How does
this justify 0**0 being equal to 0.5?

I know how to justify 0 and 1, and NaN (on the basis that both 0 and 1
can be justified). I don't follow how other values can be used.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decimals and other numbers

2015-01-08 Thread Ben Finney
Devin Jeanpierre jeanpierr...@gmail.com writes:

 decimal.InvalidOperation: 0 ** 0

 I'd file a bug report but I'm anticipating some rational (heh)
 explanation. Any ideas?

First note that it's explicitly documented as an invalid operation
URL:file:///usr/share/doc/python3-doc/html/library/decimal.html#decimal.InvalidOperation.
So someone has at least thought about it and deliberately decided it
should be so.

Why that should be, I don't know; I think the correct behaviour is for
‘0 ** 0 == 1’. But perhaps someone else has a better explanation for why
Decimal should behave differently from ‘int’ and ‘float’ here.

-- 
 \  “I bought a self learning record to learn Spanish. I turned it |
  `\on and went to sleep; the record got stuck. The next day I |
_o__)   could only stutter in Spanish.” —Steven Wright |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


[issue14262] Allow using decimals as arguments to `timedelta`

2014-10-14 Thread Stefan Krah

Changes by Stefan Krah stefan-use...@bytereef.org:


--
nosy:  -skrah

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue14262
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Working with decimals part 2

2014-08-27 Thread Seymore4Head
On Tue, 26 Aug 2014 10:46:56 +1000, alex23 wuwe...@gmail.com wrote:

On 26/08/2014 3:55 AM, Seymore4Head wrote:
 I changed the program just a little to give myself a little practice
 with number formats.  The main thing I wanted to do was make the
 decimal points line up.  The problem I am having is with the print
 (count)(payment)(balance) line.

While I don't want to discourage you from learning how to do it the long 
way, when you have a handle on it I highly recommend using a library for 
producing tabular data. tabulate is a very handy one, which supports 
lining up decimal points, amongst many other features:

https://pypi.python.org/pypi/tabulate

I personally find formatting text to be a pain and will always look for 
a better method.

Thanks for this link.

For some reason, I didn't see this message the day I started this
thread.  I am still rechecking questions I have asked.

I don't think I am ready for this yet, but hopefully soon.
-- 
https://mail.python.org/mailman/listinfo/python-list


Working with decimals part 2

2014-08-25 Thread Seymore4Head
import sys
import math
def row1(number):
return str(number).rjust(3)
def row2(number):
return str(format(number) ',.2f'))
def row3(number):
return '${:.2f}'.format(number)
def row4(number):
return '$' + str(format(math.floor(number * 100) / 100, ',.2f'))

count = 0
payment = 0
borrowed = 100
rate = 6
term = 12
interest=borrowed*rate*.01   #(*1)
balance = borrowed + interest
print (Loan calculator)
print ()
print (Amount borrowed: , borrowed)
print (Interest rate: , rate)
print (Term: (months), term)
print ()
print (Amount borrowed: , borrowed)
print (Total interest paid: , interest)
print ()
print ()
print (Amount  Remaining)
print (Pymt#PaidBalance)
print (-   --   --)
while count =term:

print ({} {} {}.format(row1(count),
row2(payment),row3(balance)))

payment = (borrowed + interest)/term
balance = balance - payment
count = count + 1


I changed the program just a little to give myself a little practice
with number formats.  The main thing I wanted to do was make the
decimal points line up.  The problem I am having is with the print
(count)(payment)(balance) line.

I added 4 functions row1-4 for some practice in formatting.
Row4 is the old makeitmoney function.  I am not using it, but I am
keeping it in.

row2 is row4 with: 
(math.floor(number * 100) / 100, ',.2f')
taken out leaving',.2f'
For some reason, it is not working.  If I try to use row2 I get this
error:
http://i.imgur.com/FgeF9c9.jpg

Most of my learning is trial and error.  Mostly error.  To try to get
the decimals to line up, I changed row3 from'${:.2f}' to '${:6.2f}'.
That makes the decimals line up, but it adds another problem.
http://i.imgur.com/1KsP3ga.jpg

If you change borrowed from 100 to 1000 the fix gets broken again.
So I changed the '${:6.2f}' to '${:8.2f}'
http://i.imgur.com/74C5sAx.jpg

That works until you change borrowed to 100
http://i.imgur.com/fCuwOXv.jpg
Is there a way to fix the decimal point to line up without having to
limit the whole digits?

BTW I changed row3 back to  '${:6.2f}' and used 1 000 000 000 for
borrowed  It doesn't lose any digits in the whole number column, but
it does skew the formatting.
http://i.imgur.com/Hjpkts4.jpg
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Working with decimals part 2

2014-08-25 Thread Chris Angelico
On Tue, Aug 26, 2014 at 3:55 AM, Seymore4Head
Seymore4Head@hotmail.invalid wrote:
 For some reason, it is not working.  If I try to use row2 I get this
 error:
 http://i.imgur.com/FgeF9c9.jpg

Several meta-issues.

Firstly, your subject line talks about 'decimal' again. You're
actually working with floats; Python has a quite separate decimal
module, and it's not what you're doing here. It's confusing for those
of us who know that you're actually working in binary floating point
:)

Secondly: An image is a really bad way to capture an error message.
Instead of saying it is not working and uploading a screenshot to
imgur, just copy and paste the exception into the body of the email.

Thirdly: If you're working iteratively, keep the files as simple as
possible, and if you can do this as one-liners in Idle's interactive
mode, that's probably the easiest way to show us what's happening.
Don't bury all of them in together into a single program.

As to your actual issue... it's a little unclear, because the system's
interpretation of what you've written is completely different from
yours - due to one misplaced bracket.

 str(format(number), ',.2f'))

You want to format the number .2f, not str the formatted number .2f. I
think you can figure it out from there :)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Working with decimals part 2

2014-08-25 Thread Mark Lawrence

On 25/08/2014 18:55, Seymore4Head wrote:

import sys
import math
def row1(number):
 return str(number).rjust(3)
def row2(number):
 return str(format(number) ',.2f'))
def row3(number):
 return '${:.2f}'.format(number)
def row4(number):
 return '$' + str(format(math.floor(number * 100) / 100, ',.2f'))

count = 0
payment = 0
borrowed = 100
rate = 6
term = 12
interest=borrowed*rate*.01   #(*1)
balance = borrowed + interest
print (Loan calculator)
print ()
print (Amount borrowed: , borrowed)
print (Interest rate: , rate)
print (Term: (months), term)
print ()
print (Amount borrowed: , borrowed)
print (Total interest paid: , interest)
print ()
print ()
print (Amount  Remaining)
print (Pymt#PaidBalance)
print (-   --   --)
while count =term:

 print ({} {} {}.format(row1(count),
row2(payment),row3(balance)))

 payment = (borrowed + interest)/term
 balance = balance - payment
 count = count + 1


I changed the program just a little to give myself a little practice
with number formats.  The main thing I wanted to do was make the
decimal points line up.  The problem I am having is with the print
(count)(payment)(balance) line.

I added 4 functions row1-4 for some practice in formatting.
Row4 is the old makeitmoney function.  I am not using it, but I am
keeping it in.

row2 is row4 with:
(math.floor(number * 100) / 100, ',.2f')
taken out leaving',.2f'
For some reason, it is not working.  If I try to use row2 I get this
error:
http://i.imgur.com/FgeF9c9.jpg

Most of my learning is trial and error.  Mostly error.  To try to get
the decimals to line up, I changed row3 from'${:.2f}' to '${:6.2f}'.
That makes the decimals line up, but it adds another problem.
http://i.imgur.com/1KsP3ga.jpg

If you change borrowed from 100 to 1000 the fix gets broken again.
So I changed the '${:6.2f}' to '${:8.2f}'
http://i.imgur.com/74C5sAx.jpg

That works until you change borrowed to 100
http://i.imgur.com/fCuwOXv.jpg
Is there a way to fix the decimal point to line up without having to
limit the whole digits?

BTW I changed row3 back to  '${:6.2f}' and used 1 000 000 000 for
borrowed  It doesn't lose any digits in the whole number column, but
it does skew the formatting.
http://i.imgur.com/Hjpkts4.jpg



The best approach to trial and error is to use the interactive prompt. 
You'll need something like it if you insist on mixing function calls 
that contain various types of string formatting with string formatting.


An alternative is to apply the KISS principle.

print ({x}{y}{z}.format(count, payment, balance)) is all you need, 
where x, y and z are the appropriate formatting options for each of 
count, payment and balance.  These options have already been pointed out 
to you.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: Working with decimals part 2

2014-08-25 Thread MRAB

On 2014-08-25 18:55, Seymore4Head wrote:

import sys
import math
def row1(number):
 return str(number).rjust(3)
def row2(number):
 return str(format(number) ',.2f'))


That line has to many ')'.

The result of 'format' is a string, so there's no need to use 'str'.


def row3(number):
 return '${:.2f}'.format(number)
def row4(number):
 return '$' + str(format(math.floor(number * 100) / 100, ',.2f'))


Here, again, the result of 'format' is a string, so there's no need to 
use 'str'.


count = 0
payment = 0
borrowed = 100
rate = 6
term = 12
interest=borrowed*rate*.01   #(*1)
balance = borrowed + interest
print (Loan calculator)
print ()
print (Amount borrowed: , borrowed)
print (Interest rate: , rate)
print (Term: (months), term)
print ()
print (Amount borrowed: , borrowed)
print (Total interest paid: , interest)
print ()
print ()
print (Amount  Remaining)
print (Pymt#PaidBalance)
print (-   --   --)
while count =term:

 print ({} {} {}.format(row1(count),
row2(payment),row3(balance)))

 payment = (borrowed + interest)/term
 balance = balance - payment
 count = count + 1


I changed the program just a little to give myself a little practice
with number formats.  The main thing I wanted to do was make the
decimal points line up.  The problem I am having is with the print
(count)(payment)(balance) line.

I added 4 functions row1-4 for some practice in formatting.
Row4 is the old makeitmoney function.  I am not using it, but I am
keeping it in.

row2 is row4 with:
(math.floor(number * 100) / 100, ',.2f')
taken out leaving',.2f'
For some reason, it is not working.  If I try to use row2 I get this
error:
http://i.imgur.com/FgeF9c9.jpg

Most of my learning is trial and error.  Mostly error.  To try to get
the decimals to line up, I changed row3 from'${:.2f}' to '${:6.2f}'.
That makes the decimals line up, but it adds another problem.
http://i.imgur.com/1KsP3ga.jpg

If you change borrowed from 100 to 1000 the fix gets broken again.
So I changed the '${:6.2f}' to '${:8.2f}'
http://i.imgur.com/74C5sAx.jpg

That works until you change borrowed to 100
http://i.imgur.com/fCuwOXv.jpg
Is there a way to fix the decimal point to line up without having to
limit the whole digits?

BTW I changed row3 back to  '${:6.2f}' and used 1 000 000 000 for
borrowed  It doesn't lose any digits in the whole number column, but
it does skew the formatting.
http://i.imgur.com/Hjpkts4.jpg


There are 2 steps:

1. Format the amount as a string. This is best done in a function.

2. Right-justify the string. This could be done as part of the format
for the row.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Working with decimals part 2

2014-08-25 Thread alex23

On 26/08/2014 3:55 AM, Seymore4Head wrote:

I changed the program just a little to give myself a little practice
with number formats.  The main thing I wanted to do was make the
decimal points line up.  The problem I am having is with the print
(count)(payment)(balance) line.


While I don't want to discourage you from learning how to do it the long 
way, when you have a handle on it I highly recommend using a library for 
producing tabular data. tabulate is a very handy one, which supports 
lining up decimal points, amongst many other features:


https://pypi.python.org/pypi/tabulate

I personally find formatting text to be a pain and will always look for 
a better method.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Working with decimals

2014-08-24 Thread Larry Hudson

On 08/23/2014 02:13 PM, Seymore4Head wrote:

On Sat, 23 Aug 2014 13:47:20 -0400, Seymore4Head

I found this function that I will be saving for later.
def make_it_money(number):
 import math
 return '$' + str(format(math.floor(number * 100) / 100, ',.2f'))

(I still need more practice to find out how it does what it does, but
I like the end result)


That's total nonsense and overkill!  If you really want to do it with a separate function, using 
old style:


def make_it_money(number):
return '$%.2f' % number

or using new style:

def make_it_money(number):
return '${:.2f}'.format(number)

But even these functions are unnecessary.  Use either of these formatting methods directly in 
the print() statement...




So I changed the line in question to:
  print (repr(count).rjust(3), make_it_money(payment).rjust(13),
make_it_money(balance).rjust(14))


print('{:3d} ${:13.2f} ${:14.2f}'.format(count, payment, balance))

or

print('%3d $%-13.2f $%-14.2f' % (count, payment, balance))

But please, please, PLEASE first go through a real tutorial, and WORK the examples to fix them 
in your mind.  Questions like these will all be covered there.  And you'll learn the language as 
a whole instead of trying to be spoon-fed isolated answers.  It will be well worth your time.


The tutorial on the official Python web site is a good one (of course there are 
many others)

docs.python.org/3/tutorial/index.html

It does appear that you're using Py3, but in case you're using Py2, change the '3' in that URL 
to '2'.


(Print formatting is in section 7)

 -=- Larry -=-

PS.  Oops, my bad...  I just double checked my suggestions, which left-justified the values, but 
I see you want them right-justified (which keeps the decimal points lined up).  This complicates 
it a bit to keep the dollar-sign butted up against the value, and it makes it necessary to use 
that make_it_money() function I said was unnecessary.  But it's still unnecessary by using a 
little different finagling...  Try either of these versions:


print('{:3d} {:13s} {:14s}'.format(count,
'$' + str(round(payment, 2)), '$' + str(round(balance, 2

print('%3d %13s %14s' % (count, '$' + str(round(payment, 2)), '$' + 
str(round(balance, 2


--
https://mail.python.org/mailman/listinfo/python-list


Re: Working with decimals

2014-08-24 Thread Seymore4Head
On Sun, 24 Aug 2014 00:04:29 -0700, Larry Hudson org...@yahoo.com
wrote:

On 08/23/2014 02:13 PM, Seymore4Head wrote:
 On Sat, 23 Aug 2014 13:47:20 -0400, Seymore4Head

 I found this function that I will be saving for later.
 def make_it_money(number):
  import math
  return '$' + str(format(math.floor(number * 100) / 100, ',.2f'))

 (I still need more practice to find out how it does what it does, but
 I like the end result)

That's total nonsense and overkill!  If you really want to do it with a 
separate function, using 
old style:

def make_it_money(number):
 return '$%.2f' % number

or using new style:

def make_it_money(number):
 return '${:.2f}'.format(number)

But even these functions are unnecessary.  Use either of these formatting 
methods directly in 
the print() statement...


 So I changed the line in question to:
   print (repr(count).rjust(3), make_it_money(payment).rjust(13),
 make_it_money(balance).rjust(14))

print('{:3d} ${:13.2f} ${:14.2f}'.format(count, payment, balance))

or

print('%3d $%-13.2f $%-14.2f' % (count, payment, balance))

But please, please, PLEASE first go through a real tutorial, and WORK the 
examples to fix them 
in your mind.  Questions like these will all be covered there.  And you'll 
learn the language as 
a whole instead of trying to be spoon-fed isolated answers.  It will be well 
worth your time.

The tutorial on the official Python web site is a good one (of course there 
are many others)

docs.python.org/3/tutorial/index.html

It does appear that you're using Py3, but in case you're using Py2, change the 
'3' in that URL 
to '2'.

(Print formatting is in section 7)

  -=- Larry -=-

PS.  Oops, my bad...  I just double checked my suggestions, which 
left-justified the values, but 
I see you want them right-justified (which keeps the decimal points lined up). 
 This complicates 
it a bit to keep the dollar-sign butted up against the value, and it makes it 
necessary to use 
that make_it_money() function I said was unnecessary.  But it's still 
unnecessary by using a 
little different finagling...  Try either of these versions:

print('{:3d} {:13s} {:14s}'.format(count,
 '$' + str(round(payment, 2)), '$' + str(round(balance, 2

print('%3d %13s %14s' % (count, '$' + str(round(payment, 2)), '$' + 
str(round(balance, 2

Thanks for sharing these.  I tried every single one.
The first two you gave didn't format correctly (as you noted) but it
seems like they should have.
If I understand this one:
print('{:3d} ${:13.2f} ${:14.2f}'.format(count, payment, balance))
the ${:13.2f} part would have lined up correctly if the number had 13
digits before the decimal.  The leading 0's were ignored.  

The last two hit the spot when the last digit is not a 0.  When the
last digit is a 0, it causes the decimals not to line up.

Tiny quirks like that can really be frustrating if you are trying to
deliver a polished product.  Luck for me, I am not.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Working with decimals

2014-08-24 Thread Seymore4Head
On Sun, 24 Aug 2014 00:04:29 -0700, Larry Hudson org...@yahoo.com
wrote:

On 08/23/2014 02:13 PM, Seymore4Head wrote:
 On Sat, 23 Aug 2014 13:47:20 -0400, Seymore4Head

 I found this function that I will be saving for later.
 def make_it_money(number):
  import math
  return '$' + str(format(math.floor(number * 100) / 100, ',.2f'))

 (I still need more practice to find out how it does what it does, but
 I like the end result)

That's total nonsense and overkill!  If you really want to do it with a 
separate function, using 
old style:

def make_it_money(number):
 return '$%.2f' % number

or using new style:

def make_it_money(number):
 return '${:.2f}'.format(number)

But even these functions are unnecessary.  Use either of these formatting 
methods directly in 
the print() statement...


 So I changed the line in question to:
   print (repr(count).rjust(3), make_it_money(payment).rjust(13),
 make_it_money(balance).rjust(14))

print('{:3d} ${:13.2f} ${:14.2f}'.format(count, payment, balance))

or

print('%3d $%-13.2f $%-14.2f' % (count, payment, balance))

But please, please, PLEASE first go through a real tutorial, and WORK the 
examples to fix them 
in your mind.  Questions like these will all be covered there.  And you'll 
learn the language as 
a whole instead of trying to be spoon-fed isolated answers.  It will be well 
worth your time.

The tutorial on the official Python web site is a good one (of course there 
are many others)

docs.python.org/3/tutorial/index.html

It does appear that you're using Py3, but in case you're using Py2, change the 
'3' in that URL 
to '2'.

(Print formatting is in section 7)

  -=- Larry -=-

PS.  Oops, my bad...  I just double checked my suggestions, which 
left-justified the values, but 
I see you want them right-justified (which keeps the decimal points lined up). 
 This complicates 
it a bit to keep the dollar-sign butted up against the value, and it makes it 
necessary to use 
that make_it_money() function I said was unnecessary.  But it's still 
unnecessary by using a 
little different finagling...  Try either of these versions:

print('{:3d} {:13s} {:14s}'.format(count,
 '$' + str(round(payment, 2)), '$' + str(round(balance, 2

print('%3d %13s %14s' % (count, '$' + str(round(payment, 2)), '$' + 
str(round(balance, 2

I almost moved, but I was looking at the print out again for this one:
print('%3d $%-13.2f $%-14.2f' % (count, payment, balance))

I can't understand why the $%-13.2f is pushed against the first
column, but the $%-14.2f is not.  It seems like the first case ignores
the leading 0s and the second case doesn't not.


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Working with decimals

2014-08-24 Thread Joshua Landau
On 23 August 2014 23:53, Chris Angelico ros...@gmail.com wrote:
 On Sun, Aug 24, 2014 at 8:47 AM, Joshua Landau jos...@landau.ws wrote:
 On 23 August 2014 23:31, Chris Angelico ros...@gmail.com wrote:
 I'd say never is too strong (there are times when it's right to put
 an import inside a function), but yes, in this case it should really
 be at the top of the function.

 But do any of them apply to import math?

 Yep. If you have only one function that will ever use it, and that
 function often won't ever be called, then putting the import inside
 the function speeds up startup. Anything that cuts down on I/O can
 give a dramatic performance improvement.

 python -c import time; a = time.time(); import math; b = time.time(); 
 print(b-a)
0.0005981922149658203

*squints eyes*

Is math not already imported by start-up?

 However, you won't need the import at all if you let the formatting
 function do the rounding for you.

 Can that floor?

 I'm not sure, dig into the format spec and see!

FWIW, I haven't seen something that does so.
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   >