• Post Reply Bookmark Topic Watch Topic
  • New Topic

Trapezoidal Rule implementation in Java - need help  RSS feed

 
Greenhorn
Posts: 24
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
I have found this code for implementing the trapezoidal rule of numerical integration:


The code above was copied from the web page: http://www.cs.usfca.edu/~peter/cs220/code/trap/Trap.java

All I have changed in the code is the function to be integrated -> (8+4cos(x))
and added the line to handle the cos(x) function.

When run I give the values of 0 (for a), 1.57 (for b) and it throws an exception at this point.

Here is the exception:


What can I do for this?
Thanks
 
Master Rancher
Posts: 2046
75
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Alexandros,

to my surprise I got exactly the same error. It has to with the Locale that the Scanner is using. In my Windows settings, I have a dot as decimal separator, but my Locale is 'nl-NL' and that seems to have the comma as separator.

So, use 3,4 instead of 3.4 and you should be fine (hopefully).

have absolutely no problems with a dot.

Unfortunately, I saw no clear way to make the Scanner use my Windows settings. I hope a Scanner specialist can explain how to handle this in a satisfying way.
 
Piet Souris
Master Rancher
Posts: 2046
75
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By the way:
in java 8 you can turn the function into a parameter Function<Double, Double>, so you're not stuck to the current cos-function. For instance:

And you would call it like this:
 
Alexandros Stefanidis
Greenhorn
Posts: 24
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Piet,

by changing the seperator from a dot to a comma works
now just fine!
Thanks
 
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I had written that code, I would make sure to hide it away where nobody could see it. I would be embarrassed to expose it to public gaze.
The exception is caused by your entering the arguments in the wrong order. The message telling you to enter three numbers is confusing at best; you are supposed to enter double double int in that order.

Moving to one of our Java® fora.

Yes, there is a way to get keyboard input reliably via a Scanner object. Start by searching my posts for those containing both Scanner and utility class.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!