I would like to create a list of all the real numbers between 1.0 and 2.0 in two-decimal-place increments. This
dList = [1.00,1.01..2.00]
however, creates float run-on problems
dList = [1.0,1.01,1.02,1.03,1.04,1.05,1.06,1.07,1.08,1.09,1.1,1.11,1.12,
1.1300000000000001,1.1400000000000001,1.1500000000000001, ...
To remedy this I found what I thought was a function in Data.Decimal namely, roundTo. I was hoping to eventually run this
map (roundTo 2) [1.1,1.2..2.0]
and get rid of the float run-on, but it produces a giant error message. This page is for this beginner undecipherable. And so I'm trying to do this with an hs file loaded at a ghci REPL. This is the code
import Data.Decimal
dList :: [Decimal]
dList = [1.00,1.01..2.0]
main = print dList
and it produces
Could not find module ‘Data.Decimal’
Lost, I am....
Note
This answer is an FYI for all of you beginners simply trying to follow along in a beginner Haskell book that has you typing code into a text editor, firing up the ghci REPL and doing :load my-haskell-code.hs.
YMMV Solution
As can be gleaned above, Data.Decimal is not a standard included Prelude sort of package. It must be loaded independently -- and no, it doesn't work to simply put import Data.Decimal at the top of your code. As leftaroundabout said in a comment above, the very simplest way for Haskell beginners not yet doing projects is to start ghci thusly
stack ghci --package Decimal
Of course YMMV depending on how you installed Haskell. I installed Haskell through the stack project management, hence, the stack before ghci --package Decimal. Another unique thing about my setup is I'm using Emacs org-mode's Babel code blocks, which is largely the same as the basic type-and-load way, i.e., non-project. I did try to alter Emacs's haskell-process-args-stack-ghci which is in haskell-customize.el by just adding --package Decimal but it didn't work. Instead, I simply went to my bash command line and put in stack ghci --package Decimal, then I restarted a separate org-mode Babel ghci and it worked. Now,
dList :: [Decimal]
dList = [1.00,1.01..2.00]
> dList
[1,1.01,1.02,1.03,1.04,1.05,1.06,1.07,1.08,1.09,1.10,1.11,1.12,1.13,1.14,1.15,1.16,1.17,1.18,1.19,1.20,1.21,1.22,1.23,1.24,1.25,1.26,1.27,1.28,1.29,1.30,1.31,1.32,1.33,1.34,1.35,1.36,1.37,1.38,1.39,1.40,1.41,1.42,1.43,1.44,1.45,1.46,1.47,1.48,1.49,1.50,1.51,1.52,1.53,1.54,1.55,1.56,1.57,1.58,1.59,1.60,1.61,1.62,1.63,1.64,1.65,1.66,1.67,1.68,1.69,1.70,1.71,1.72,1.73,1.74,1.75,1.76,1.77,1.78,1.79,1.80,1.81,1.82,1.83,1.84,1.85,1.86,1.87,1.88,1.89,1.90,1.91,1.92,1.93,1.94,1.95,1.96,1.97,1.98,1.99,2.00]
no muss, no fuss. I killed the ghci and loaded it without the --package Decimal and it still knew about Decimal, so this change is recorded quasi-permanently in my ~/.stack directory somewhere? Oddly, the bash ghci session doesn't know about the *haskell* ghci session in org-mode. Also, when just using the Emacs haskell mode stand-alone for type-and-load, its ghci session also doesn't play well with the org-mode ghci. I've gone with the minimalist Emacs org-mode babel because it seems better than just lhs literal Haskell. If anyone knows how to make literal Haskell sing like org-mode, I'd like to know.
Postmortem
I guess I insisted on figuring out Decimal because in researching the whole rounding issue I started seeing a wild divergence of suggested solutions (not necessarily here, but other places) and scary technical arguments. Decimal seemed the simplest in a wild storm of competing rounding strategies. Rounding should be simple, but in Haskell it turned into a time-sucking trip down multiple rabbit holes.
Answer to your specific float problem
By far the simplest option in this case is
[n/100 | n<-[0..200]]
or variations on the same idea:
map (/100) [0..200]
(*1e-2) . fromIntegral <$> [0 .. 200 :: Int] -- (*) is more efficient than (/),
-- but will actually introduce rounding
-- errors (non-accumulating) again
No need for any special decimal library or rational numbers.
The reason this works better than the [x₀, x₁ .. xe] approach is that integers below 252 can be expressed exactly in floating point (whereas decimal fractions cannot). Therefore, the range [0..200] is exactly what you want it to be. Then at the end, dividing each of these numbers by 100 will still not give you exact representations of the hundredths you want to get – because such representations don't exist – but you will for each element get the closest possible approximation. And that closest possible approximation is in fact printed in x.yz form, even with the standard print function. By comparison, in [1.00,1.01..2.0] you keep adding up already-approximate values, thereby compounding the errors.
You could also use your original range calculation in exact rationals, and only then convert them to float★ – this still doesn't require a decimal library
map fromRational [0, 0.01 .. 2]
Rational arithmetic is often an easy fix for similar problems – but I tend to advise against this, because it usually scales badly. Algorithms that have rounding problems in floating-point will more often than not run into memory problems in rational arithmetic, because you need to carry an ever-growing range of precision through the entire calculation. The better solution is to avoid needing the precision in the first place, like with the n/100 suggestion.
Also, arguably the [x₀, x₁ .. xe] syntax is a broken design anyway; integer ranges have far clearer semantics.
Note also that the float errors in your original attempt aren't necessarily a problem at all. An error of 10-9 in a real-world measured quantity is for all meaningful purposes neglectable. If you need something to be truely exact, you probably shouldn't be using fractional values at all, but straight integers. So, conside Carl's suggestion of just living with the float-deviations, but simply printing them in a suitably rounded form, by way of showFFloat, printf, or Text.Show.Pragmatic.print.
★Actually, in this specific case both solutions are almost equivalent, because converting Rational to float involves floating-point dividing the numerator by the denominator.
Answer to your module-loading problem
In cases where you do need the Decimal library (or some other library), you need to depend on it.
The easiest way to do this is to use Stack and add Decimal to your global project. Then, you can load the file with stack ghci and it'll know where to look for Data.Decimal.
Alternatively, and IMO preferrably, you should create a project package yourself and only make that depend on Decimal. This can be done with either Stack or Cabal-install.
$ mkdir my-decimal-project
$ cd my-decimal-project
$ cabal init
Now you're being asked some questions about the name etc. of your project, you can mostly answer with the defaults. Say your project defines a library (you can add an executable later on if you want.)
cabal init creates amongst other things a my-decimal-project.cabal file. In that file, add Decimal to the dependency, and your own source file to exposed-modules.
Then you need to (still in your project directory) cabal install --dependencies-only to fetch the Decimal library, and then cabal repl to load your module.
I've been wanting to make a block type game for a while now but have never understood how to actually make one. I have googled forever and there is not much and what is there comes with a stipulation that I am not wanting to bother with (gpl license, entire code base, AND the license in any project, bleh). So I took to a forums with my problem. I did not know it, but I was trying to make a Puyo Puyo type game. With blocks dropping from the ceiling and then clearing if there's a match of 3 or more. I had no idea on how to do the matching. Which is what I wanted to know. A very nice, charming, and intelligent fellow provided me with this:
http://hastebin.com/ziyejejoxu.js
Granted, that's quite a lot, but the way he managed to code it allowed me to somewhat grasp it. However, there is a single infuriating problem. One, exactly ONE, line of code does not compile and breaks. I asked him if I could email him about it and he said okay. I haven't go a response yet so I may not be getting one so I'm taking this here. Here is how I am using the code so far. There are two parts, the play state, and the puzzle piece:
http://pastebin.com/SvMR9mMb
The program breaks in the playstate, giving this error:
source/PlayState.hx:291: characters 33-52 : Array access is not allowed on x : Int -> Int
What I have tried:
I had assumed that it was not allowed because the puzzle piece x is a float, and of course, you can't push a float into an int array. So what I did was simply in the puzzle piece first, convert the the float to an int. That did not work. THEN in the state, I switched the float to an int. That did not work. As an exercise, I attempted to convert a Flixel game to HaxeFlixel to see if I could learn anything. I probably did it wrong and did not.
So the question is: Why does that line not compile and what do I need to do to make it compile or to achieve it's intended purpose?
The syntax is wrong. push is a function, and function calls use (). [] is for array access (hence the error message).
This should work:
if (this_piece_is_in_a_match) matched_pieces.push(_i);
So I'm just getting started learning Fortran because apparently it's still used for a lot of scientific computing. One of the things that I already hate about it is that compared to C++, strings are a nightmare. At the moment, I'm just trying to find a simple way to read in a string provided by the user and then spit it back out without all the trailing whitespace.
Here's the code I have right now, which according to what I've read should work under later Fortran standards, i.e. 2003/2008 (though I could easily have made errors of which I'm unaware). I'm trying to compile it on the MinGW version of gfortran that came with Code::Blocks 13.12.
program tstring
implicit none
character(100) io_name
character(len=:), allocatable :: final_name
print *, "What is your name, O master?"
read *, io_name
final_name = trim(io_name)
print *, "Excellent, master ", final_name, "!"
end program
It compiles just fine, but still has a massive amount of whitespace between final_name and the "!". The whitespace is somewhat dependent on the number of characters I give to io_name, but not in a particularly logical manner (15 characters gives more whitespace than 30, for example). Particularly bewildering to me is that if I give certain numbers of characters to io_name (between about 17 and 22) then instead of printing out the name, the program runs into a segfault.
Perhaps the most difficult part of this for me is that good Fortran documentation is very hard to find, especially for the 2003 and later standards. So if anybody could point me to some good documentation, I'd really appreciate it!
Get a more recent compiler. Gfortran 4.8 (AFAIK the oldest supported version) should work just fine with your code.
Strings are not really any nightmare, just stop thinking in C++ and trying to translate that in Fortran. It is quite possible to write tokenizers, parsers and DSL interpreters in Fortran.
Regarding the resources, it is off-topic here and there are numerous books and tutorials out there. Search for Fortran Resources at http://fortranwiki.org/fortran/show/HomePage
I'm doing some monad stuff in Haskell and I wrote a function that calculates the probability of winning a gambling game given the game's decision tree. It works like a charm, except for the fact that it sometimes returns SLIGHTLY different answers than expected. For example, I'm uploading my code to DOMjudge and it returns an error, saying that the correct answer should be 1 % 6 instead of 6004799503160661 % 36028797018963968, which is what my function is returning. If you actually do the division they're both nearly the same, but I don't understand why my answer is still slightly different. I've been messing around with different types (using Real instead of Int for example), but so far no luck. I'm kind of new to this stuff and I can't seem to figure this out. Can anyone point me in the right direction?
-code deleted-
You're losing precision due to the division in probabilityOfWinning. You have the right solution to avoiding it---using type Rational = Ratio Integer---but you're applying it too late in the game. By converting toRational after division you've already lost your precision before you converted to Rational.
Try something like this
import Data.Ratio
probabilityOfWinning tree = countWins tree % countGames tree
And then remove the Real type restrictions from countWins and countGames so that they return whole integers instead of floating point numbers. These together will make sure you always use infinite precision math instead of floating point.
I'm considering porting a rather unwieldy bash script to python but I'm stuck on how to handle the following aspect: The point of the script is to generate a png image depending on dynamically fetched data. The bash script grabs the data, and builds a very long invocation of the convert utility, with lots of options. It seemed like python's template strings would be a good solution (I would vastly prefer to stay within the standard library, since I'll be deploying to shared hosting), but I discovered that you can't evaluate expressions as you can in bash:
>>> from string import Template
>>> s = Template('The width times one is ${width}')
>>> s.substitute(width=45)
'The width times one is 45'
>>> t = Template('The width times two is ${width*2}')
>>> t.substitute(width=45)
# Raises ValueError
Since my bash script depends quite heavily on such arithmetic (otherwise the number of variables to keep track of would increase exponentially) I'd like to know if there's a way to emulate this behavior in python. I saw that this question, asking roughly the same, has a comment, reading:
This would be very unPythonic, because it's counterintuitive -- strings are just
strings, they shouldn't run code!
If this is the case, what would be a more idiomatic way to approach this problem?
The proposed answer to the question linked above is to use string formatting with either the % syntax or the format() function, but I don't think that would work well with the number of variables in my string (around 50).
Why not use built-in string formatting?
width = 45
"Width times one is {width}".format(width=width)
"Width times two is {width}".format(width=2*width)
results in
Width times one is 45
Width times two is 90
The Pythonic solution to this problem is to forget about string formatting and pass a list of arguments to one of the subprocess functions, e.g.
# I have no idea about convert's command line usage,
# so here's an example using echo.
subprocess.call(["echo", str(1 + 1), "bla"])
That way, there's no need to build a single string and no need to worry about quoting.
You probably need a better templating engine. Jinja2 supports this kind of stuff and a lot more. I don't think the standard library has anything equally powerful, but from what I figured, the library is pure Python, so you can integrate it into your application by just copying it along.
If Jinja doesn't fit you for some reason, have a look at the Python wiki, which has a section specifically for those kinds of libraries. Amongst them is the very lightweight Templite, which is only one class and seems to do exactly what you need.
The task is not that hard, why don't you just make some coding for fun? And here is the function almost does what you want.
import re
def TempEval(template,**kwargs):
mark = re.compile('\${(.*?)}')
for key in kwargs:
exec('%s=%s'%(key,kwargs[key]))
for item in mark.findall(template):
template=template.replace('${%s}'%item,str(eval(item)))
return template
print TempEval('The width times one is ${width}',width=5)
#The width times one is 5
print TempEval('The width times two is ${width*2}',width=5)
#The width times two is 10