Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

redphoenix11 posted:

Also, I read that the last push is to provide a dummy return address for the syscall, which I guess the subl instruction accomplishes as well.

Nah, it's what I said, it's for the convenience of libc, which is pretty reasonable. The BSD-derived Unices tend to design syscalls that way, which has the disadvantage of making it impossible to be significantly smarter than libc.

redphoenix11 posted:

eax holds the error codes or the fd if it works, which is why it was returning 14 or 2 when it wasn't working.

How does it supposedly indicate failure? Because, you know, errnos (which are small positive integers) are not actually distinguishable from file descriptors (which are also small positive integers).

Adbot
ADBOT LOVES YOU

socialsecurity
Aug 30, 2003

I am trying to make a web form for a customer, I've made plenty in Php before but this guy is wanting nearly spreadsheet capabilities. Like if they put 20 of an item in a spot he wants it to calculate the price right there on the same window right then. I've seen this done before but am not exactly sure what I should be looking for to make it happen, even a point to the right programming langlauge would be helpful.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

socialsecurity posted:

I am trying to make a web form for a customer, I've made plenty in Php before but this guy is wanting nearly spreadsheet capabilities. Like if they put 20 of an item in a spot he wants it to calculate the price right there on the same window right then. I've seen this done before but am not exactly sure what I should be looking for to make it happen, even a point to the right programming langlauge would be helpful.

Javascript

Ringo R
Dec 25, 2005

ช่วยแม่เฮ็ดนาแหน่เดัอ
Web design question:
Is there a way to increase scroll bar size using CSS or whatever? Same effect as going to (in Windows) Windows color and appearance / Appearance / Advanced and then increasing scroll bar size. It only has to work in IE7.

Mikey-San
Nov 3, 2005

I'm Edith Head!

Ringo R posted:

Web design question:
Is there a way to increase scroll bar size using CSS or whatever? Same effect as going to (in Windows) Windows color and appearance / Appearance / Advanced and then increasing scroll bar size. It only has to work in IE7.

God, I hope not.

hey mom its 420
May 12, 2007

Short answer: No
Long answer: Nooooooooooooo!

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

Ringo R posted:

Web design question:
Is there a way to increase scroll bar size using CSS or whatever? Same effect as going to (in Windows) Windows color and appearance / Appearance / Advanced and then increasing scroll bar size. It only has to work in IE7.

I guess you could completely reimplement the scroll bars from scratch in javascript and then make them look however you want.

Don't do this.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Plorkyeran posted:

I guess you could completely reimplement the scroll bars from scratch in javascript and then make them look however you want.

Don't do this.

Right, he should do them in Flash if he wants them to look good.

Chib
Nov 20, 2006
In a Perl regular expression, do you need to escape character a forward slash?

I know that normally you put the expression between forward slashes so, to me, if you wanted the literal character, you would put \/.

I'd just test it out, except I'm in a bit of a predicament. I'm not a programmer, I don't know anything about code, etc. I'm just an Office Manager who likes to get involved in things that are way over her head when the IT department won't pick them up.

I've installed AWStats and it's working for the most part, but since they didn't turn on virtual domain logging, I have to set up each config file to look for a specific domain in the URL. They give me the option of writing a regular expression for it, which I thought would be a nice and simple character string, but since /BKS/ and /BKSML/ both have BKS in them, I get inaccurate results.

I need to have the regular expression be "/BKS/," but I'm worried that if I use an escape character when one isn't necessary, it won't find the right thing, and I'll have to lose 10 hours worth of work if it doesn't pick up the right lines, because I'd have to start the entire thing over again since it goes sequentially.

This is what the file says:

# Include in stats, only accesses to URLs that match one of following entries.
# For example, if you want AWStats to filter access to keep only stats that
# match a particular string, like a particular directory, you can add this
# directory name in this parameter.
# The opposite parameter of "OnlyFiles" is "SkipFiles".
# Note: Use space between each value. This parameter is or not case sensitive
# depending on URLNotCaseSensitive parameter.
# Note: You can use regular expression values writing value with REGEX[value].
# Change : Effective for new updates only
# Example: "REGEX[marketing_directory] REGEX[office\/.*\.(csv|sxw)$]"
# Default: ""
#
OnlyFiles="REGEX[BKS]"

My limited understanding from googling regular expressions for an hour is that that second example shows that I do need to escape the forward slash. Does that sound right?

I'm really sorry if this is a stupid question, I've been learning as I go, and I'm kind of struggling along with this stuff.

baquerd
Jul 2, 2007

by FactsAreUseless
A perl regular expression for "/BKS/" is \/BKS\/

Edit: If it takes 10 hours runtime to cycle through your directory structure, you're doing something wrong.

baquerd fucked around with this message at 19:16 on Jan 23, 2009

Chib
Nov 20, 2006

quadreb posted:

A perl regular expression for "/BKS/" is \/BKS\/

Edit: If it takes 10 hours runtime to cycle through your directory structure, you're doing something wrong.

Thank you, I'll use that. My fingers are crossed!

It's not cycling through my directory structure, unless I misunderstand what that means. The way I understand it, it's analyzing 9 months worth of logs from a website with heavy traffic, going line by line. I can excuse it taking 10 hours. I just hope it'll go a little faster once I start it going on my home PC as well.

Edit: It's also currently running in low-priority mode on an old rear end server. :(

Chib fucked around with this message at 20:07 on Jan 23, 2009

baquerd
Jul 2, 2007

by FactsAreUseless

Chib posted:

Thank you, I'll use that. My fingers are crossed!

It's not cycling through my directory structure, unless I misunderstand what that means. The way I understand it, it's analyzing 9 months worth of logs from a website with heavy traffic, going line by line. I can excuse it taking 10 hours. I just hope it'll go a little faster once I start it going on my home PC as well.

Edit: It's also currently running in low-priority mode on an old rear end server. :(

I suppose you could have a combination of hardware + operating system + file size issues that would make a well-designed program take that long, but I bet you could speed it up anywhere from 2-100x regardless by utilizing a good sysadmin or programmer for the job. Also, you should be buffering the output to file and you should be able to check the output as you go.

Chib
Nov 20, 2006

quadreb posted:

I suppose you could have a combination of hardware + operating system + file size issues that would make a well-designed program take that long, but I bet you could speed it up anywhere from 2-100x regardless by utilizing a good sysadmin or programmer for the job. Also, you should be buffering the output to file and you should be able to check the output as you go.

We have only one woman in our IT department. Not only is she very swamped, she's very bad at what she does, anyway. Ultimately, I'm more capable than she is.

Because this project isn't that important, they don't want to drop any cash on it to hire a contractor to set us up with something really good. I'm pretty quick to catch on to things so when we found out that we were too big for Google Analytics, I started looking for other options. IT can't handle it, so implementation falls to me. I say "OK, set up logging for these options," and she tries about 5 different log formats over the course of 4 months, without giving me access to the logs. It's the new year, and we need to have results, but the logging situation has gotten so out of hand that I'm going to have to manually run every config file (there are about 50 currently) 5 times, changing the log format options between runs, in order to salvage the data from the last 9 months.

I would LOVE to have a better solution aside from telling the president that she can't have the data from before 01/01/09. I'll learn whatever I have to learn to make this whole thing work better. But it has to be free, and it has to have an HTML output that the program managers find as pleasing as Google Analytics was. That's why, as far as I know, I'm stuck running over these old log files to get to a suitable starting place for everything to run automatically.

Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?
My code is very intimate with the database. (It manages the data going in and cleans it up.) And it's getting very messy/cumbersome. So I was thinking about making an abstract layer between the business logic and the raw database calls, to make maintaining database changes a lot easier. So my code will just ask questions, without knowing how they're implemented, and this layer will obviously sit on a DB.

What's this layer called? I've heard this advice doled out many times, but now that I actually need it, I want to look up more definitive sources to make sure I'm not missing out on any patterns or practices.

bitprophet
Jul 22, 2004
Taco Defender

Triple Tech posted:

My code is very intimate with the database. (It manages the data going in and cleans it up.) And it's getting very messy/cumbersome. So I was thinking about making an abstract layer between the business logic and the raw database calls, to make maintaining database changes a lot easier. So my code will just ask questions, without knowing how they're implemented, and this layer will obviously sit on a DB.

What's this layer called? I've heard this advice doled out many times, but now that I actually need it, I want to look up more definitive sources to make sure I'm not missing out on any patterns or practices.

An object-relational mapper (ORM) is typically what this is called, assuming I'm reading you correctly. Not sure what a non-object-oriented version would be called, if such things exist.

For example, Storm (I think it's...Java? Perl?) and SQLAlchemy or SQLObject (Python).

Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?
I just talked with a coworker about this. I'm not necessarily doing ORM work, but it's the same concept. ORM is a specific implementation of the word I want. I guess otherwise I'll just go around calling it "the database layer that's not actually the database itself but a front for it in code-space".

Edit: And a tiny bit of Googling leads us to database abstraction layer. I guess that's pretty succinct and accurate.

Triple Tech fucked around with this message at 22:46 on Jan 23, 2009

hey mom its 420
May 12, 2007

DB abstraction layer? If you know what you're going to put in it and how it's going to work, it doesn't matter what you call it.

EDIT: You beat me with your edit. AAA!

covener
Jan 10, 2004

You know, for kids!

Chib posted:

In a Perl regular expression, do you need to escape character a forward slash?

If you use something other then / as your delimiter, you can use / as a literal

foo =~ m@/foo/bar@/a/b/c@;

Note that foo =~ /foo/bar/ is shorthand for m/foo/bar/, but he 'm' becomes mandatory if you pick a different delimiter.

Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?
Should one object class have functionality that depends on its data (like one method implemented with a switch statement) or should that behavior be outlined in two different subclasses, and then I make a factory to decide which one gets created?

Pweller
Jan 25, 2006

Whatever whateva.
I need a for loop with a counter in a batch file, but I'm missing something with my counter, here's my script,

(it generates a numbered list of words from a text file)

code:
@ECHO OFF
SET count=1
FOR /F "eol=; skip=1 delims=, " %%i in (names.txt) DO (
  ECHO %count%^) %%i
  SET /a count+=1
)
ECHO %count% elements
pause

output posted:

1) apple
1) banana
1) cucumber
3 elements
Press any key to continue...

Why is my count not being outputted correctly until after the loop?

e: stripped/simplified code for clarity

Pweller fucked around with this message at 18:11 on Jan 26, 2009

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Triple Tech posted:

Should one object class have functionality that depends on its data (like one method implemented with a switch statement) or should that behavior be outlined in two different subclasses, and then I make a factory to decide which one gets created?

A third option is to extract the behavior into an unrelated class and have the original class delegate to an instance of that.

Anyway, this really can't be decided at this level of generality. Unless you're under pretty strong code-stability constraints, though, I would just do the simplest thing and keep an eye up for chances to refactor.

Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!

Pweller posted:

I need a for loop with a counter in a batch file, but I'm missing something with my counter, here's my script,

(it generates a numbered list of words from a text file)

code:
@ECHO OFF
SET count=1
FOR /F "eol=; skip=1 delims=, tokens=1,2" %%i in (names.txt) DO (
  ECHO %count%^) %%i   ^(%%j^)
  SET /a count+=1
)
ECHO %count% elements
pause
Why is my count not being outputted correctly until after the loop?

You need Delayed Variable Expansion

Pweller
Jan 25, 2006

Whatever whateva.

Jethro posted:

You need Delayed Variable Expansion

excellent thank you, this works now

code:
@ECHO OFF
setlocal enabledelayedexpansion
SET count=1
FOR /F "eol=; delims=, " %%i in (names.txt) DO (
  ECHO !count!^) %%i
  SET /a count+=1
)
ECHO %count%
pause

ZentraediElite
Oct 22, 2002

I am trying to redo some JavaScript I accidentally deleted, and I am stuck on a little statement.

I am doing this within Microsoft Dynamics CRM 4.0 on the OnChange of one of my fields.

code:
if ((crmForm.FormType >= 1) && (crmForm.FormType <= 4))
{

var value = crmForm.all.new_accounttype.DataValue;

crmForm.all.tab3Tab.style.display = (value == "1") ? "none" : "";
crmForm.all.tab3Tab.style.display = (value == "2") ? "" : "none";
crmForm.all.tab3Tab.style.display = (value == "3") ? "" : "none";

}
From my understanding, this should be hiding the tab on values 2 and 3 and showing it on 1. But, it's hiding it on 1 and 2 and showing it on 3. Help!

Message me on AIM @ ZentraediElite if you can, i'm befuddled!

POKEMAN SAM
Jul 8, 2004

ZentraediElite posted:

I am trying to redo some JavaScript I accidentally deleted, and I am stuck on a little statement.

I am doing this within Microsoft Dynamics CRM 4.0 on the OnChange of one of my fields.

code:
if ((crmForm.FormType >= 1) && (crmForm.FormType <= 4))
{

var value = crmForm.all.new_accounttype.DataValue;

crmForm.all.tab3Tab.style.display = (value == "1") ? "none" : "";
crmForm.all.tab3Tab.style.display = (value == "2") ? "" : "none";
crmForm.all.tab3Tab.style.display = (value == "3") ? "" : "none";

}
From my understanding, this should be hiding the tab on values 2 and 3 and showing it on 1. But, it's hiding it on 1 and 2 and showing it on 3. Help!

Message me on AIM @ ZentraediElite if you can, i'm befuddled!

Look at the left hand of each of the three assignments:

crmForm.all.tab3Tab.style.display

You're only assigning to tab3Tab's style, not tab1Tab and tab2Tab. :)

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
You've got three assignment statements in a row, each changing the value of crmForm.all.tab3Tab.style.display. The most recent assignment statement always wins, so your code is equivalent to:

code:
if ((crmForm.FormType >= 1) && (crmForm.FormType <= 4))
{
var value = crmForm.all.new_accounttype.DataValue;

crmForm.all.tab3Tab.style.display = (value == "3") ? "" : "none";
}
There are several ways to do what you want, but this should be good enough:

code:
var displayValue;
switch (crmForm.all.new_accounttype.DataValue) {
  case "1": displayValue = "none"; break;
  case "2": displayValue = ""; break;
  case "3": displayValue = ""; break;
}
crmForm.all.tab3Tab.style.display = displayValue;

ZentraediElite
Oct 22, 2002

rjmccall posted:

You've got three assignment statements in a row, each changing the value of crmForm.all.tab3Tab.style.display. The most recent assignment statement always wins, so your code is equivalent to:

code:
if ((crmForm.FormType >= 1) && (crmForm.FormType <= 4))
{
var value = crmForm.all.new_accounttype.DataValue;

crmForm.all.tab3Tab.style.display = (value == "3") ? "" : "none";
}
There are several ways to do what you want, but this should be good enough:

code:
var displayValue;
switch (crmForm.all.new_accounttype.DataValue) {
  case "1": displayValue = "none"; break;
  case "2": displayValue = ""; break;
  case "3": displayValue = ""; break;
}
crmForm.all.tab3Tab.style.display = displayValue;

CRM didn't save/publish right on my first attempt, but it looks like i'm good to go now! Thanks!

EDIT:

Quick question though. How do I account for a null? When I do
code:
case "" ...
it freaks.

ZentraediElite fucked around with this message at 04:04 on Jan 27, 2009

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

ZentraediElite posted:

How do I account for a null? When I do
code:
case "" ...
it freaks.

The colon is part of the case syntax; you'd need to have case "": .... But "" is a completely different concept from null in JavaScript.

tef
May 30, 2004

-> some l-system crap ->
I wrote http://logo.twentygototen.org, and I've been asked to kludge it to make it work with speech recognition.

Right now we're using a hack - a fixed vocabulary in osx' speakable items, that sends the right keys to firefox.

I've been pointed at the following, and it looks like a start: http://www.w3.org/TR/wai-aria/ , but I would be thankful at any other information out there.

The plan is to change from a text-box to an almost command-line like interaction, a bit like working in a shell. We might have to change the syntax slightly to support this.

I'm also looking at proprietary sr software, or a series of convoluted hacks to take it forward.

Does anyone have any experience in speech driven environments ?
or how to hook into osx's speech recognition a little deeper ?
or in general any ideas about how to essentially write a speech driven code editor ?

edit: http://web.archive.org/web/20080213071927/voicecode.iit.nrc.ca/VoiceCode/public/ywiki.cgi

tef fucked around with this message at 06:48 on Jan 27, 2009

Boywunda
Jun 25, 2003

First thing first - Total scripting newbie here.

Background - I work in a Data Security Administration department and deleting multiple users and their home file data, which all reside on different file servers.

I need to write a script to remove the share on a file share, then delete the contents of the folder. For multiple file shares, all read from a *.csv file. I've googled this to death already, and after never done ANY VB scripting before, came up with the following (copying different VB scripts that I've found by googling it), which removes the share, but only reading 1 line, and does not delete the contents.

code:
dim fs,objTextFile
set fs=CreateObject("Scripting.FileSystemObject")
dim arrStr
set objTextFile = fs.OpenTextFile("Book1.csv")

Do while NOT objTextFile.AtEndOfStream
  arrStr = split(objTextFile.ReadLine,",")
  DomainName = arrStr(0)
  ServerName = arrStr(1)
  ShareName = arrStr(2)
Loop

objTextFile.Close
set objTextFile = Nothing
set fs = Nothing

Set cont = GetObject("WinNT://"& DomainName &"/"& ServerName &"/LanmanServer,FileService")
cont.Delete "FileShare", ""& ShareName &"
csv line looks like this:
domainname, servername, sharename

This script works to remove the share, but that's it. Anything that someone can share to also remove the contents of the folder, and for multiple lines, would be greatly appreciated!

Boywunda fucked around with this message at 14:32 on Jan 27, 2009

Zoracle Zed
Jul 10, 2001

Knux_The_Echidna posted:

I am absolutely horrified by MATLAB and all of its components. I'm having some issues writing an m-file for a specific logistic function which needs to graph multiple iterations of population growth and map it as a cobweb diagram. To save asking a horrific number of questions in this thread given that I'm new to programming and every answer I get is bound to just evoke more :downs: from me, would anyone familiar with MATLAB be happy to chat with me over an IM program of their choice?

Thanks in advance.
I don't use any IM programs but feel free to PM me with any questions. There used to be a pretty good 'stupid Matlab questions' in E&A, bump that if you can find it or start a new one.

Super Dude
Jan 23, 2005
Do the Jew
(C++)I am trying to grab characters from a string I am reading in from redirecting the cin to a file. Say I have the string "Test" in the file in.txt. I can read the string into my 'string temp' variable. I can write the string to out.txt file as well. My problem is that I want, say, T from the string.

cout << temp[0];

It gives me the following error in gedit when I try to open out.txt

Could not open the file out.txt
gedit has not been able to detect the character encoding.

When I cout to the console, it works fine, but it won't work when writing to a file. What am I doing wrong?

Red Alert
Mar 3, 2007
I have a question about Haskell.

I'm supposed to make a program that utilizes newton's method for approximating function evaluations.

Basically what I need is a function that constantly improves a value until it gets to its desired result. It takes a function that improves a value, a function that decides when a value is close enough to the actual one, and it returns a function that takes a value and returns an improved value.

Here's what I have so far:

deriv :: (Float->Float) -> (Float->Float)
deriv f = \x -> (f(x+0.0001) - f x)/0.0001

newton :: (Float -> Float) -> Float -> Float
newton f x = iterativeImprove goodEnough x improve f x

iterativeImprove :: (Float -> Bool) -> (Float -> Float) -> (Float -> Float)
iterativeImprove g f


goodEnough :: Float -> (Float -> Bool)
goodEnough x = \guess -> abs (guess - x) < 0.001

improve :: (Float -> Float) -> (Float -> Float)
improve f = \guess -> guess - f(guess)/(deriv f(guess))

----

I'm pretty sure I have my goodEnough and improve functions right, but I'm not quite sure how to implement them into iterativeImprove. Any help?

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

Red Alert posted:

Basically what I need is a function that constantly improves a value until it gets to its desired result. It takes a function that improves a value, a function that decides when a value is close enough to the actual one, and it returns a function that takes a value and returns an improved value.

code:
import Data.List

iterativeImprove :: (Float -> Bool) -> (Float -> Float) -> (Float -> Float)
iterativeImprove goodEnough improve initialValue = head $ dropWhile (not . goodEnough) $ unfoldr (\v -> Just (v, improve v)) initialValue
Reading from right to left: We start with the initial value. We create an infinite list of values by accumulating calls to the improve function. We discard values from the head of this list until we find something good enough. We return that value.

Note that I would probably split this into two functions: One that just does the unfoldr stuff, and one that does the dropWhile and head. It's occasionally useful to deal with an infinite lazy list of values for stuff like this rather than just the least-good-enough value.

Edit: Also, all your deriv, goodEnough, and improve functions would be more normally written without those lambdas but just doing all the pattern matching left of the equals. Haskell lets you curry functions, so the type a -> (b -> c) is the same as a -> b -> c.

ShoulderDaemon fucked around with this message at 08:11 on Jan 28, 2009

Red Alert
Mar 3, 2007
Thanks for the quick response, but that seems a little too complicated at this time. I'm just starting the 4th week of this class and haven't learned anything about Just or $.

Also, I'm not really sure how to do the pattern matching after the equals. Would I just do something like this?

improve f = guess -> guess - f(guess)/(deriv f(guess))

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

Red Alert posted:

Thanks for the quick response, but that seems a little too complicated at this time. I'm just starting the 4th week of this class and haven't learned anything about Just or $.

"a b c $ d e f" is shorthand for, essentially, "a b c (d e f)". The Just is sort of an uninteresting part of the type required by unfoldr.

Red Alert posted:

Also, I'm not really sure how to do the pattern matching after the equals. Would I just do something like this?

improve f = guess -> guess - f(guess)/(deriv f(guess))

You've got your parenthesis a bit mixed up, what you want is:
improve f = \guess -> guess - (f guess) / (deriv (f guess))
which is the same as
improve f guess = guess - (f guess) / (deriv (f guess))
which is the same as
improve f guess = guess - (f guess) / (deriv $ f guess)
if that helps you understand $ and currying at all.

Anyway, we can rewrite iterativeImprove as a few simpler functions.

Have you been taught about lazy lists yet? We can write:
code:
improvedValues :: (Float -> Float) -> Float -> [Float]
improvedValues improve initialValue = initialValue : map improve (improvedValues improve initialValue)
This creates an infinite list of values, starting with an initial value, and improving it by one step each time, using recursion. The unfoldr function is just sort of shorthand for this kind of thing.
Edit: Durr, I'm sort of dumb right now.

Now that we have this improvedValues function, we can use it:
code:
firstGoodEnough :: (Float -> Bool) -> [Float] -> Float
firstGoodEnough goodEnough (x:xs) = if goodEnough x
                                      then x
                                      else firstGoodEnough goodEnough xs
Again, we're using recursion and a list. This time we consume the list one element at a time, check if the value is good enough, if it is we return it, otherwise we check the rest of the list. The head and dropWhile function do the same thing, or you can use find, or a few other similar functions.

Finally, we can put it all together:
code:
iterativeImprove :: (Float -> Bool) -> (Float -> Float) -> Float -> Float
iterativeImprove goodEnough improve initialValue = firstGoodEnough goodEnough (improvedValues improve initialValue)
This is just sticking our helper functions together so they do what we want.

ShoulderDaemon fucked around with this message at 08:42 on Jan 28, 2009

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender
Here's how I would solve the problem. I'm going to spoiler the actual definitions for the sake of your homework assignment; you should be able to write these functions on your own given the types and explanations.

We will calculate the square root of n based on Newton's method to find a root of x^2 - n.

> rootFunc :: Float -> Float -> Float
> rootFunc n x = x^2 - n

Newton's method requires the derivative of our target function. The derivative of x^2 - n is simply 2x by first-year calculus.
I include the n parameter simply for consistency with rootFunc, and to generalize to other applications than square roots.

> rootFunc' :: Float -> Float -> Float
> rootFunc' n x = 2 * x

This is our initial crappy guess for the square root of a number.

> guess :: Float -> Float
> guess n = n / 2

Newton's method operates by iterative improvement on a guess.

> improve :: (Float -> Float) -> (Float -> Float) -> Float -> Float
> improve f f' x = x - (f x) / (f' x)

Now, we can construct an infinite list of successive improvements.

> successiveImprovements :: (Float -> Float) -> Float -> [Float]
> successiveImprovements improve initialValue = initialValue : map improve (successiveImprovements improve initialValue)

The generalized Newton's method: Given a function to find the root of, that function's derivative, and a guess, produce an infinite list of estimates.

> newtonMethod :: (Float -> Float) -> (Float -> Float) -> Float -> [Float]
> newtonMethod f f' guess = successiveImprovements (improve f f') guess

Given an infinite list of successive improvements, we want to remove the high-error values at the start.
We do this by dropping elements until the difference between elements is no more than some epsilon.

> reduceError :: Float -> [Float] -> [Float]
> reduceError epsilon (x1:x2:xs) = if abs (x1 - x2) >= epsilon then reduceError epsilon (x2:xs) else (x1:x2:xs)

I'll define a global epsilon, here.

> epsilon :: Float
> epsilon = 0.000001

Now, we produce the infinite list of estimates of the square root of a number, using Newton's method.

> newtonRootEstimates :: Float -> [Float]
> newtonRootEstimates n = newtonMethod (rootFunc n) (rootFunc' n) (guess n)

We restrict those estimates to the "good enough" estimates.

> newtonRootGoodEstimates :: Float -> [Float]
> newtonRootGoodEstimates n = reduceError epsilon (newtonRootEstimates n)

Finally, we simply take the first such "good enough" estimate, and use that as the Newton root.

> newtonRoot :: Float -> Float
> newtonRoot n = head (newtonRootGoodEstimates n)

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Super Dude posted:

(C++)I am trying to grab characters from a string I am reading in from redirecting the cin to a file. Say I have the string "Test" in the file in.txt. I can read the string into my 'string temp' variable. I can write the string to out.txt file as well. My problem is that I want, say, T from the string.

cout << temp[0];

It gives me the following error in gedit when I try to open out.txt

Could not open the file out.txt
gedit has not been able to detect the character encoding.

When I cout to the console, it works fine, but it won't work when writing to a file. What am I doing wrong?

That just sounds like a problem with gedit's encoding guessing functionality choking on files that are very small. If you run 'cat out.txt' you should just get the T as you expect. There might be a way to turn off the encoding detection in gedit if you feel you must use it.

dealmaster
Dec 24, 2005

Somebody call for an exterminator?
I'm working in C# and am having a bitch of a time with rounding numbers properly. Apparently Math.Round(4.5) returns 4, which is loving mindboggling and I can't understand why it would do such a thing. Does anyone know of a quick, easy way to round the way the rest of the world rounds so that calling Math.Round(4.5) returns 5? Essentially it's rounding down with a decimal of 0.5 instead of rounding up. I have never seen this behavior before.

What my problem boils down to is I'm trying to round this number:

4151.385

to 2 decimal places. I call Math.Round(4151.385, 2) and get back 4151.38. Because this is part of a big calculation, it fucks up everything downwind of this.

Adbot
ADBOT LOVES YOU

Vanadium
Jan 8, 2005

^^^ Apparently there is an extra parameter to let you control that behaviour? http://msdn.microsoft.com/en-us/library/ef48waz8.aspx

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply